/**
 * Created by TRwin7SP1 on 2016/7/28.
 */



/*
 * 2016-9-12 巫瑜
 * 阅片UI界面交互事件处理
 *
 *
 * */
(function (lmViewer) {
  var ui = lmViewer.ui;

  ui.config = {
    buttons: [
      {
        id: "grid",
        icon: "glyphicon glyphicon-th",
        clickEvent: "lmViewer.ui.changeLayout()",
        txt: "多窗口"
      },
      {
        id: "enableScrollStack",
        icon: "fa fa-sort-amount-asc",
        clickEvent: "",
        txt: "滚动浏览"
      },
      {
        id: "enableWindowLevelTool",
        icon: "glyphicon glyphicon-adjust",
        clickEvent: "",
        txt: "对比度"
      },
      {
        id: "zoom",
        icon: "glyphicon glyphicon-zoom-in",
        clickEvent: "",
        txt: "放大/缩小"
      },
/*            {
       id:"move",
       icon:"",
       clickEvent:"",
       txt:"移动位置"
       },*/
      /*      {
       id:"scan",
       icon:"",
       clickEvent:"",
       txt:"浏览"
       },
       {
       id:"other",
       icon:"",
       clickEvent:"",
       txt:"其它"
       },*/
      {
        id: "pan",
        icon: "glyphicon glyphicon-move",
        clickEvent: "",
        txt: "移动"
      },
      {
        id: "autoPlay",
        icon: "glyphicon glyphicon-play-circle",
        clickEvent: "lmViewer.ui.autoPlayClick()",
        txt: "自动播放"
      },
      {
        id: "RotateLeft",
        icon: "fa fa-rotate-left",
        clickEvent: "",
        txt: "左旋"
      },
      {
        id: "RotateRight",
        icon: "fa fa-rotate-right",
        clickEvent: "",
        txt: "右旋"
      },
      {
        id: "vFlip",
        icon: "fa fa-arrows-v",
        clickEvent: "",
        txt: "上下翻转"
      },
      {
        id: "hFlip",
        icon: "fa fa-arrows-h",
        clickEvent: "",
        txt: "左右翻转"
      },
      {
        id: "invert",
        icon: "fa fa-delicious",
        clickEvent: "",
        txt: "反色"
      },
      {
        id: "reset",
        icon: "fa fa-refresh",
        clickEvent: "",
        txt: "重置"
      },
      {
        id: "cornerMark",
        icon: "fa fa-font",
        clickEvent: "",
        txt: "角标"
      },
      {
        id: "getDicom",
        icon: "",
        clickEvent: "",
        txt: "获取DICOM原片"
      },
      {
        id: "enableLength",
        icon: "fa fa-expand",
        clickEvent: "lmViewer.ui.cornerMarkClick()",
        txt: "长度"
      },
      {
        id: "probe",
        icon: "fa fa-map-marker",
        clickEvent: "",
        txt: "像素值测量"
      },
      {
        id: "circleroi",
        icon: "fa fa-circle-o",
        clickEvent: "",
        txt: "椭圆框"
      },
      {
        id: "rectangleroi",
        icon: "fa fa-square-o",
        clickEvent: "",
        txt: "矩形框"
      },
      {
        id: "angle",
        icon: "glyphicon glyphicon-chevron-left",
        clickEvent: "",
        txt: "角度测量"
      },
      {
        id: "ShowAnnotation",
        icon: "glyphicon glyphicon-eye-open",
        clickEvent: "",
        txt: "可见"
      },
      {
        id: "UnShowAnnotation",
        icon: "glyphicon glyphicon-eye-close",
        clickEvent: "",
        txt: "不可见"
      },
      {
        id: "wwwc",
        icon: "fa fa-plus-square-o",
        clickEvent: "",
        txt: "局部对比度"
      },
      {
        id: "synchronizer",
        icon: "glyphicon glyphicon-transfer",
        clickEvent: "lmViewer.ui.synchronizerClick()",
        txt: "序列同步"
      },
      {
        id: "referenceLine",
        icon: "fa fa-i-cursor",
        clickEvent: "lmViewer.ui.referenceLineClick()",
        txt: "定位线"
      },
      {
        id: "threeViews",
        icon: "glyphicon glyphicon-tasks",
        clickEvent: "lmViewer.ui.threeViewsClick()",
        txt: "三视图"
      },
      {
        id: "saveImg",
        icon: "glyphicon glyphicon-download",
        clickEvent: "",
        txt: "影像保存"
      },
      /* {
       id:"WindowLevelHead",
       icon:"",
       clickEvent:"",
       txt:"头部",
       img: 'img/viewer/BK_Head.png'
       },
       {
       id:"WindowLevelLung",
       icon:"",
       clickEvent:"",
       txt:"肺部",
       img: 'img/viewer/BK_Brain.png'
       },
       {
       id:"WindowLevelChest",
       icon:"",
       clickEvent:"",
       txt:"胸腔",
       img: 'img/viewer/BK_Thorax.png'
       },
       {
       id:"WindowLevelAbdomen",
       icon:"",
       clickEvent:"",
       txt:"腹部",
       img: 'img/viewer/BK_Abdomen.png'
       },
       {
       id:"WindowLevelBone",
       icon:"",
       clickEvent:"",
       txt:"骨",
       img: 'img/viewer/BK_Spine.png'
       },
       {
       id:"resetWWWL",
       icon:"fa fa-history",
       clickEvent:"",
       txt:"重置对比度",
       },
       {
       id:"pageUp",
       icon:"glyphicon glyphicon-arrow-up",
       clickEvent:"",
       txt:"上一张",
       },
       {
       id:"pageDown",
       icon:"glyphicon glyphicon-arrow-down",
       clickEvent:"",
       txt:"下一张",
       }*/
    ]
  }

  ui.moveClick = function () {
    /**
     * version:1.0
     * date:2016-8-12
     * auth:tangzhengxiong
     * desc:移动分类按钮
     *
     * */
    $("#pan").fadeToggle("quick");
    $("#RotateRight").fadeToggle("quick");
    $("#RotateLeft").fadeToggle("quick");
    $("#vFlip").fadeToggle("quick");
    $("#hFlip").fadeToggle("quick");
    $("#cornerMark").fadeToggle("quick");
    $("#getDicom").fadeToggle("quick");
  };
  ui.scanClick = function () {
    /**
     * version:1.0
     * date:2016-8-12
     * auth:tangzhengxiong
     * desc:浏览分类按钮
     *
     * */
    $("#enableLength").fadeToggle("quick");
    $("#probe").fadeToggle("quick");
    $("#circleroi").fadeToggle("quick");
    $("#rectangleroi").fadeToggle("quick");
    $("#angle").fadeToggle("quick");
    $("#ShowAnnotation").fadeToggle("quick");
    $("#UnShowAnnotation").fadeToggle("quick");
  };
  ui.otherClick = function () {
    /**
     * version:1.0
     * date:2016-8-12
     * auth:tangzhengxiong
     * desc:
     *
     * */
    $("#invert").fadeToggle("quick");
    $("#wwwc").fadeToggle("quick");
    $("#synchronizer").fadeToggle("quick");
    $("#referenceLine").fadeToggle("quick");
    $("#threeViews").fadeToggle("quick");
    $("#saveImg").fadeToggle("quick");
    $("#reset").fadeToggle("quick");
  };
  ui.liTabInfoClick = function () {
    /**
     * version:1.0
     * date:2016-8-12
     * auth:tangzhengxiong
     * desc:
     *
     * */
    $("#toolbar-function").css("display", "none");
  };
  ui.liTabReportClick = function () {
    /**
     * version:1.0
     * date:2016-8-12
     * auth:tangzhengxiong
     * desc:
     *
     * */
    $("#toolbar-function").css("display", "none");
  };
  ui.liTabSReportClick = function () {
    /**
     * version:1.0
     * date:2016-8-12
     * auth:tangzhengxiong
     * desc:浏览分类按钮
     *
     * */
    $("#toolbar-function").css("display", "none");
  };
  ui.liTabImageClick = function () {
    /**
     * version:1.0
     * date:2016-8-12
     * auth:tangzhengxiong
     * desc:
     *
     * */
    $("#toolbar-function").css("display", "block");
  };
  ui.changeLayout = function () {
    /**
     * version:1.0
     * date:2016-8-12
     * auth:tangzhengxiong
     * desc:display the layout
     *
     * */
    $('#grid').css('background-color', 'gray');

    lmViewer.ui.cancelBindKey();
    lmViewer.ui.loadButtonHint();
    jQuery('#contentDiv').html('');
    jQuery('#contentDiv').load('/app/main/Viewer/layout.html');
    jQuery('#contentDiv').show();

    jQuery("#contentDiv").mouseleave(function () {
      jQuery(this).hide();
    });
  };
  ui.changeTable = function () {
    /**
     * version:1.0
     * date:2016-8-12
     * auth:tangzhengxiong
     * desc:display the layout
     *
     * */
    var divs = $("#series");
    var trs = divs[0].getElementsByTagName("tr");
    var len = trs.length;
    for (var i = 0; i < len; i++) {
      trs[i].onclick = function () {
        for (var j = 0; j < len; j++) {
          trs[j].style.backgroundColor = "#000";
        }
        this.style.backgroundColor = "#303030 ";
      };
    }

  };
  ui.cancelBindKey = function () {
    /**
     * version:1.0
     * date:2016-8-12
     * auth:tangzhengxiong
     * desc:取消按钮绑定事件
     *
     * */
    jQuery(document).unbind('keydown.1');
    jQuery(document).unbind('keydown.2');
    jQuery(document).unbind('keydown.3');
    jQuery(document).unbind('keydown.4');
    jQuery(document).unbind('keydown.5');
    jQuery(document).unbind('keydown.home');
    jQuery(document).unbind('keydown.end');
    jQuery(document).unbind('keydown.pageup');
    jQuery(document).unbind('keydown.left');
    jQuery(document).unbind('keydown.up');
    jQuery(document).unbind('keydown.right');
    jQuery(document).unbind('keydown.down');
    jQuery(document).unbind('keydown.R');
    $("#enableWindowLevelTool").unbind("click");
    $("#pan").unbind("click");
    $("#zoom").unbind("click");
    $("#RotateLeft").unbind("click");
    $("#RotateRight").unbind("click");
    $("#hFlip").unbind("click");
    $("#vFlip").unbind("click");
    $("#reset").unbind("click");
    $("#enableLength").unbind("click");
    $("#probe").unbind("click");
    $("#circleroi").unbind("click");
    $("#rectangleroi").unbind("click");
    $("#angle").unbind("click");
    $("#ShowAnnotation").unbind("click");
    $("#UnShowAnnotation").unbind("click");
    $("#invert").unbind("click");
    $("#WindowLevelHead").unbind("click");
    $("#WindowLevelLung").unbind("click");
    $("#WindowLevelChest").unbind("click");
    $("#WindowLevelAbdomen").unbind("click");
    $("#WindowLevelBone").unbind("click");
  };
  ui.goBack = function () {
    /**
     * version:1.0
     * date:2016-8-12
     * auth:tangzhengxiong
     * desc:This function is used to display the hint when relevant button is pressed ------Updated by TanQilu
     *
     * */
    if (null == image2askid || '' == image2askid || 'null' == image2askid) {
      window.history.go(-1);
    } else {
      window.history.go(-2);
    }
  };
  ui.loadButtonHint = function () {
    /**
     * version:1.0
     * date:2016-8-12
     * auth:tangzhengxiong
     * desc:用于点击工具栏按钮时显示提示
     *
     * */
    $("#enableWindowLevelTool").click(function () {
      if (lmViewer.data.queryParams.imageType === 'jpg' && lmViewer.data.iWindowVNum * lmViewer.data.iWindowHNum > 1) {
        humane.log('多窗口下jpg不支持明对比度功能', {timeout: 2000});
        return;
      }
      humane.log("点击鼠标左键，然后滑动，调整窗宽/窗位", {timeout: 1000})
    });
    $("#pan").click(function () {
      humane.log("点击鼠标左键，然后滑动，调整图像位置", {timeout: 1000})
    });
    $("#zoom").click(function () {
      humane.log("滑动，图像放大/缩小", {timeout: 1000})
    });
    $("#RotateLeft").click(function () {
      humane.log("影像左旋转", {timeout: 1000})
    });
    $("#RotateRight").click(function () {
      humane.log("影像右旋转", {timeout: 1000})
    });
    $("#hFlip").click(function () {
      humane.log("影像左右翻转", {timeout: 1000})
    });
    $("#vFlip").click(function () {
      humane.log("影像上下翻转", {timeout: 1000})
    });
    $("#reset").click(function () {
      humane.log("重置影像的位置", {timeout: 1000})
    });
    $("#enableLength").click(function () {
      humane.log("长度测量", {timeout: 1000})
    });
    $("#probe").click(function () {
      humane.log("CT值测量", {timeout: 1000})
    });
    $("#angle").click(function () {
      humane.log("角度测量", {timeout: 1000})
    });
    $("#ShowAnnotation").click(function () {
      humane.log("显示所有的标记", {timeout: 1000})
    });
    $("#UnShowAnnotation").click(function () {
      humane.log("关闭所有的标记", {timeout: 1000})
    });
    $('#wwwc').click(function () {
      humane.log("局部调节窗宽/窗位", {timeout: 1000})
    });
    $("#WindowLevelHead").click(function () {
      humane.log("头颈部 窗宽/窗位=80/35", {timeout: 1000})
    });
    $("#WindowLevelLung").click(function () {
      humane.log("肺部 窗宽/窗位=1500/-500", {timeout: 1000})
    });
    $("#WindowLevelChest").click(function () {
      humane.log("胸腔 窗宽/窗位=500/50", {timeout: 1000})
    });
    $("#WindowLevelAbdomen").click(function () {
      humane.log("腹部 窗宽/窗位=350/50", {timeout: 1000})
    });
    $("#WindowLevelBone").click(function () {
      humane.log("骨 窗宽/窗位=300/1500", {timeout: 1000})
    });
    //$("#autoPlay")              .click(function(){humane.log("影像自动播放",{timeout : 1000})});
    $("#invert").click(function () {
      humane.log("影像对比度", {timeout: 1000})
    });
    $("#circleroi").click(function () {
      humane.log("椭圆框", {timeout: 1000})
    });
    //$("#threeViews")              .click(function(){humane.log("三视图",{timeout : 1000})});
    $("#getDicom").click(function () {
      if (lmViewer.data.queryParams.imageType == 'dicom') {
        humane.log("获取DICOM原片", {timeout: 1000})
      } else if (lmViewer.data.queryParams.imageType == 'jpg') {
        humane.log("获取jpg", {timeout: 1000})
      }
    });
  };
  ui.imageSaveAs = function () {
    var filename = '下载'
    if (elementChoosed === '') {
      var element = $('#image00').get(0);
      cornerstoneTools.saveAs(element, filename);
    } else {
      cornerstoneTools.saveAs(elementChoosed, filename);
    }
    // recoverButtonColor();
    // $('#saveImg').css('background-color','gray');
    // clearIconsColor('saveImg');
    // $("#imageSaveAs").modal('hide');
    // var filename = $("#imageSaveAsName").val();
    // if(elementChoosed === ''){
    // 	var element = $('#image00').get(0);
    // 	cornerstoneTools.saveAs(element, filename);
    // }else{
    // 	cornerstoneTools.saveAs(elementChoosed, filename);
    // }
  };
  ui.plottingScale = function (obj) {
    /**
     * version:1.0
     * date:2016-8-12
     * auth:tangzhengxiong
     * desc:This function is used to display plotting scales in each viewport -------------- Updated by TanQilu
     *
     * */
    try {
      var _obj = {
        element: obj.element,
        image: undefined
      };
      // get the series number and instance number
      var imgIndex = lmViewer.fn.getImgIndex(_obj);

      // get the series number and instance number
      var instanceNum = imgIndex.instance;
      var seriesNum = imgIndex.series;

      // achieve the image information
      //		var row = cornerstone.getImage(element).rows;
      //		var column = cornerstone.getImage(element).columns;
      var row = parseFloat(tagArray[seriesNum][instanceNum].rows);
      var column = parseFloat(tagArray[seriesNum][instanceNum].columns);

      var rowSpacing = parseFloat(tagArray[seriesNum][instanceNum].pixelSpacing.split('\\')[0]);
      var columnSpacing = parseFloat(tagArray[seriesNum][instanceNum].pixelSpacing.split('\\')[1]);
      //		var rowSpacing = cornerstone.getImage(element).rowPixelSpacing;
      //		var columnSpacing = cornerstone.getImage(element).columnPixelSpacing;

      // 如果是JPG格式，校准坐标系
      var rowScale = 1;
      var columnScale = 1;
      if (cornerstone.getImage(obj.element).data == undefined) { // JPG
        var jpgRow = cornerstone.getImage(obj.element).rows;
        var jpgColumn = cornerstone.getImage(obj.element).columns;
        rowScale = row / jpgRow;
        columnScale = column / jpgColumn;
      }

      // the width of the scale div
      var zoom = cornerstone.getEnabledElement(obj.element).viewport.scale;
      var len = column / columnScale * zoom;
      // the left margin of the scale div
      var viewportWidth = $('#' + obj.element.id).find('canvas').width();
      var sideMargin = parseInt((viewportWidth - len) / 2) > 0 ? parseInt((viewportWidth - len) / 2) : 0;

      $('#scaleDiv' + obj.element.id.substring(5)).remove();

      // scale div
      var scaleDiv = $('<div></div>');
      scaleDiv.attr('id', 'scaleDiv' + obj.element.id.substring(5));
      scaleDiv.attr('style', 'position: absolute; bottom: 6px; left:' + sideMargin + 'px; right:' + sideMargin + 'px; height: 40px;');
      scaleDiv.appendTo($('#' + obj.element.id));

      // scale canvas, in which we plot the scale
      var scale = $('<canvas></canvas>');
      scale.attr('id', 'scale' + obj.element.id.substring(5));
      scale.attr('width', (len + 40 < viewportWidth ? len + 40 : viewportWidth).toString() + 'px');
      scale.attr('height', '40px');
      scale.appendTo($('#scaleDiv' + obj.element.id.substring(5)));

      // plot the scale
      var canvas = document.getElementById('scale' + obj.element.id.substring(5));
      var context = canvas.getContext("2d");
      context.beginPath();
      context.lineWidth = 2;
      context.strokeStyle = 'white';
      context.moveTo(0, 40);
      context.lineTo(len - 1, 40);

      // define the text style written in the canvas
      cornerstoneTools.textStyle.setFont('12px Arial');
      var font = cornerstoneTools.textStyle.getFont();
      context.font = font;
      cornerstoneTools.drawTextBox(context, 'cm', len + 15, 40 - 5, 'white');

      // draw the scale marks
      var i = 0, time = 0;
      while (i < len) {
        context.moveTo(i, 40);
        context.lineTo(i, 40 - 5);

        cornerstoneTools.drawTextBox(context, (5 * time).toString(), i, 40 - 5, 'white');

        i += 50 / (columnSpacing * columnScale) * zoom;
        time++;
      }

      context.stroke();

      // 竖屏状态下调整底部的导航栏宽度
      if (lmViewer.data.isDesktop || lmViewer.data.clientWidth < lmViewer.data.clientHeight) {
        $(' #seriesList').css('width', $(' #imageContainer').width().toString());
      }

    } catch (err) {
      // 上一段行代码有时出bug，但尚未找到问题所在，先用try catch语句临时顶替下，保证程序能够正常运行
    }
  };
  ui.getDicomClick = function () {
    /**
     * version:1.0
     * date:2016-8-12
     * auth:tangzhengxiong
     * desc:用于获取dicom或ipg图片
     *
     * */
    lmViewer.data.isGetDicomButtonPressed = true;
    lmViewer.ui.recoverButtonColor();
    $('#getDicom').css('background-color', 'gray');
    if (lmViewer.data.queryParams.imageType == 'jpg') {
      lmViewer.data.queryParams.imageType = 'dicom';
    } else {
      lmViewer.data.queryParams.imageType = 'jpg'
    }
    lmViewer.ui.showSeries();
    if ($('#getDicom').find('span').html() == 'JPG') {
      $('#getDicom').find('span').html('DCM');
    } else {
      $('#getDicom').find('span').html('JPG');
    }
  };
  ui.recoverButtonColor = function () {
    /**
     * version:1.0
     * date:2016-8-12
     * auth:tangzhengxiong
     * desc:This function is used to recover the background color of the selected button
     *
     * */
    $('#enableScrollStack').css('background-color', '#404040');
    $('#grid').css('background-color', '#404040');
    $('#enableWindowLevelTool').css('background-color', '#404040');
    $('#pan').css('background-color', '#404040');
    $('#zoom').css('background-color', '#404040');
    $('#RotateRight').css('background-color', '#404040');
    $('#RotateLeft').css('background-color', '#404040');
    $('#vFlip').css('background-color', '#404040');
    $('#hFlip').css('background-color', '#404040');
    $('#invert').css('background-color', '#404040');
    $('#reset').css('background-color', '#404040');
    $('#cornerMark').css('background-color', '#404040');
    $('#enableLength').css('background-color', '#404040');
    $('#probe').css('background-color', '#404040');
    $('#circleroi').css('background-color', '#404040');
    $('#rectangleroi').css('background-color', '#404040');
    $('#angle').css('background-color', '#404040');
    $('#ShowAnnotation').css('background-color', '#404040');
    $('#UnShowAnnotation').css('background-color', '#404040');
    $('#wwwc').css('background-color', '#404040');
    $('#synchronizer').css('background-color', '#404040');
    $('#referenceLine').css('background-color', '#404040');
    $('#saveImg').css('background-color', '#404040');
    $('#WindowLevelHead').css('background-color', '#404040');
    $('#WindowLevelLung').css('background-color', '#404040');
    $('#WindowLevelChest').css('background-color', '#404040');
    $('#WindowLevelAbdomen').css('background-color', '#404040');
    $('#WindowLevelBone').css('background-color', '#404040');
    $('#resetWWWL').css('background-color', '#404040');
    $('#threeViews').css('background-color', '#404040');
    $('#autoPlay').css('background-color', '#404040');
    $('#getDicom').css('background-color', '#404040');

  };
  ui.autoPlayClick = function () {
    /**
     * version:1.0
     * date:2016-8-12
     * auth:tangzhengxiong
     * desc:this function is used to autoPlay images
     *
     * */
    console.log('autoplay');
    lmViewer.ui.recoverButtonColor();
    $('#autoPlay').css('background-color', 'gray');
    if (lmViewer.data.iWindowHNum * lmViewer.data.iWindowHNum != 1) {
      humane.log('仅支持单窗口阅片');
      return;
    }
    if (lmViewer.data.autoPlayButtonPressed) {
      $("#autoPlay span").removeClass("hy-play").addClass("hy-stop").css("color", "#38c500");
      lmViewer.data.autoPlayButtonPressed = false;
      clearInterval(lmViewer.fn.circulatio);

      var element = $('#image00').get(0);
      var _obj = {
        element: element,
        image: undefined
      };
      lmViewer.data.wheelInstanceNum[0] = lmViewer.fn.getImgIndex(_obj).instance;
      var seriesIndex = lmViewer.fn.getImgIndex(_obj).series;
      lmViewer.fn.circulation = setInterval(function () {
        // lmViewer.fn.readjustInstanceWWWL(lmViewer.data.wheelInstanceNum[0],element);
        var _selectNewImageObj = {
          newIndex: lmViewer.data.wheelInstanceNum[0]
        }
        lmViewer.fn.selectNewImage(_selectNewImageObj);
        lmViewer.data.wheelInstanceNum[0]++;
        if (lmViewer.data.wheelInstanceNum[0] >= lmViewer.data.seriesArray[seriesIndex].instance.length) {
          lmViewer.data.wheelInstanceNum[0] = 0;
        }
      }, 100);
    } else {
      lmViewer.data.autoPlayButtonPressed = true;
      $("#autoPlay span").removeClass("hy-stop").addClass("hy-play").css("color", "#505050");
      clearInterval(lmViewer.fn.circulation);
    }
  };
  ui.threeViewsClick = function () {
    /**
     * version:1.0
     * date:2016-8-12
     * auth:tangzhengxiong
     * desc:this function is used to display MPR
     *
     * */
    var _params = lmViewer.data.queryParams;

    lmViewer.ui.recoverButtonColor();
    $('#threeViews').css('background-color', 'gray');
    if (lmViewer.data.elementChoosed == '' || lmViewer.data.iWindowHNum * lmViewer.data.iWindowVNum == 1) {
      lmViewer.data.elementChoosed = $('#image00').get(0);
    }
    var _data = {
      element: lmViewer.data.elementChoosed,
      image: undefined
    };
    var imgIndex = lmViewer.fn.getImgIndex(_data);
    var index = imgIndex.series; //series index
    var imageOrientation = lmViewer.data.tagArray[index][0].imageOrientation;
    for (var i = 1; i < lmViewer.data.tagArray[index].length; i++) {
      var Xx = parseInt(lmViewer.data.tagArray[index][0].imageOrientation.split('\\')[0]);
      var Xy = parseInt(lmViewer.data.tagArray[index][0].imageOrientation.split('\\')[1]);
      var Xz = parseInt(lmViewer.data.tagArray[index][0].imageOrientation.split('\\')[2]);
      var Yx = parseInt(lmViewer.data.tagArray[index][0].imageOrientation.split('\\')[3]);
      var Yy = parseInt(lmViewer.data.tagArray[index][0].imageOrientation.split('\\')[4]);
      var Yz = parseInt(lmViewer.data.tagArray[index][0].imageOrientation.split('\\')[5]);

      if (!(Xx == 1 && Xy == 0 && Xz == 0 && Yx == 0 && Yy == 1 && Yz == 0)) {
        humane.log('仅支持横截面序列');
        return;
      }

      if (lmViewer.data.tagArray[index][i].imageOrientation != imageOrientation) {
        humane.log('影像序列不统一');
        return;
      }
    }

    // to record the the width and height of current window, then empty it
    var imageElement = $('#' + lmViewer.data.elementChoosed.id).parent();

    var eleRowIndex = lmViewer.data.elementChoosed.id.substring(
      lmViewer.data.elementChoosed.id.indexOf('image') + 5,
      lmViewer.data.elementChoosed.id.indexOf('image') + 6);
    var eleColumnIndex = lmViewer.data.elementChoosed.id.substring(
      lmViewer.data.elementChoosed.id.indexOf('image') + 6);
    eleRowIndex = parseInt(eleRowIndex);
    eleColumnIndex = parseInt(eleColumnIndex);

    var subViewsNum = eleRowIndex * lmViewer.data.iWindowVNum + eleColumnIndex;

    var localWidth = imageElement.width();
    var localHeight = imageElement.height();

    imageElement.empty();
    imageElement.css('display', 'inline-block');
    imageElement.css('height', (localHeight - 5).toString());

    $('#toolbar-function').css('display', 'none');
    $('#toolbar-function-simple').css('display', 'block');
    $('#mrtopleft').css('display', 'none');

    // generate the structure of four sub-views
    var cnt = 0;
    var divContent = '<table id="subViews" style="width: 100%; height: 100%; border: 1px solid #D5D5D5; background-color: #000;">';
    for (var i = 0; i < 2; i++) {
      divContent += '<tr height="50%";>';
      for (var j = 0; j < 2; j++) {
        divContent += '<td style="width: 50%; border:1px solid #454444;">';
        divContent += '<div style="width:'
          + 100
          + '%;'
          + 'height:'
          + 100
          + '%'
          + ';position:relative;display:inline-block;color:white;"'
          + '>';
        divContent += '<div id="sub' + subViewsNum.toString() + cnt.toString() + '"style="position: relative;width: 100%;height: 100%;"></div></div></td>';
        cnt++;
      }
      divContent += '</tr>';
    }
    divContent += '</table>';
    imageElement.get(0).innerHTML = divContent;

    for (var i = 0; i < 4; i++) {
      var element = $('#sub' + subViewsNum.toString() + i.toString()).get(0);
      var eleWidth = $('#' + element.id).width();
      cornerstone.enable(element);
      element.style.width = eleWidth + 'px';
    }

    // generate the information div to display current image number
    var info1 = $('<div></div>');
    info1.attr('id', 'info' + subViewsNum.toString() + '1');
    info1.attr('style', 'position:absolute; color:white; bottom:6px; left:6px; width:100px; height:20px;');
    info1.appendTo($('#sub' + subViewsNum.toString() + '1'));

    var info2 = $('<div></div>');
    info2.attr('id', 'info' + subViewsNum.toString() + '2');
    info2.attr('style', 'position:absolute; color:white; bottom:6px; left:6px; width:100px; height:20px;');
    info2.appendTo($('#sub' + subViewsNum.toString() + '2'));

    var info3 = $('<div></div>');
    info3.attr('id', 'info' + subViewsNum.toString() + '3');
    info3.attr('style', 'position:absolute; color:white; bottom:6px; left:6px; width:100px; height:20px;');
    info3.appendTo($('#sub' + subViewsNum.toString() + '3'));

    // get all the images of current series
    var imageIDs = [];
    var imageData = []; // all the pixel datas of this series

    var _obj = {
      series: lmViewer.data.seriesArray[index],
      imagesid: imageIDs
    };
    lmViewer.fn.loadImages(_obj);
    for (var i = 0; i < lmViewer.data.seriesArray[index].instance.length; i++) {
      cornerstone.loadAndCacheImage(imageIDs[i]).then(function (image) {
        var pixelData = image.getPixelData();
        var idStart = image.imageId.indexOf('object=') + 7;
        var idEnd = image.imageId.indexOf('&rows');
        var objectID = image.imageId.substring(idStart, idEnd);
        var pixels =
        {
          objectID: objectID,
          pixelData: pixelData
        }
        imageData.push(pixels);

        // since all the series have been loaded, next step is to show the MPR
        if (imageData.length == lmViewer.data.seriesArray[index].instance.length) {
          _data.element = undefined;
          _data.image = image;
          var imageIdx = lmViewer.fn.getImgIndex(_data);
          var scaleV = parseFloat(lmViewer.data.thickness[imageIdx.series]);
          var scaleH = parseFloat(lmViewer.data.tagArray[imageIdx.series][imageIdx.instance].pixelSpacing.split('\\')[0]);
          var stretchScale = scaleV / scaleH;
          // sort the image series
          var tempArray = [];
          for (var i = 0; i < imageData.length; i++) {
            for (var j = 0; j < imageData.length; j++) {
              if (imageData[j].objectID == lmViewer.data.seriesArray[index].instance[i].sopIUID) {
                tempArray.push(imageData[j]);
                break;
              }
            }
          }
          imageData = tempArray;

          // build the image region which is to be showed; it is a matrix
          var width = image.width;
          var height = image.height;

          /*--------------------------------------------------------------------------------
           * generate image in the canvas of sub0
           ---------------------------------------------------------------------------------*/
          var canvas0 = cornerstone.getEnabledElement($('#sub' + subViewsNum.toString() + '0').get(0)).canvas;
          var canvas0Width = canvas0.width;
          var canvas0Height = canvas0.height;
          canvas0.width = width;
          canvas0.height = height;
          var context0 = canvas0.getContext('2d');
          var pixelDisp0 = context0.createImageData(width, height);

          // get each pixel data to be showed
          for (var i = 0; i <= (width * height - 1) * 4; i += 4) {
            pixelDisp0.data[i + 0] = imageData[parseInt(imageData.length / 2)].pixelData[i + 0];
            pixelDisp0.data[i + 1] = imageData[parseInt(imageData.length / 2)].pixelData[i + 1];
            pixelDisp0.data[i + 2] = imageData[parseInt(imageData.length / 2)].pixelData[i + 2];
            pixelDisp0.data[i + 3] = imageData[parseInt(imageData.length / 2)].pixelData[i + 3];
          }
          context0.putImageData(pixelDisp0, 0, 0);

          // change the width and height scale of imageData
          var dataURL0 = canvas0.toDataURL();
          var img0 = new Image();
          img0.src = dataURL0;
          canvas0.width = canvas0Width;
          canvas0.height = canvas0Height;

          /*--------------------------------------------------------------------------------
           * generate image in the canvas of sub1
           ---------------------------------------------------------------------------------*/
          var canvas1 = cornerstone.getEnabledElement($('#sub' + subViewsNum.toString() + '1').get(0)).canvas;
          var canvas1Width = canvas1.width;
          var canvas1Height = canvas1.height;
          canvas1.width = width;
          canvas1.height = height;
          var context1 = canvas1.getContext('2d');
          var pixelDisp1 = new Array(imageData.length);

          // get each pixel data to be showed
          for (var slice = 0; slice < imageData.length; slice++) {
            pixelDisp1[slice] = context1.createImageData(width, height);
            for (var i = 0; i <= (width * height - 1) * 4; i += 4) {
              pixelDisp1[slice].data[i + 0] = imageData[slice].pixelData[i + 0];
              pixelDisp1[slice].data[i + 1] = imageData[slice].pixelData[i + 1];
              pixelDisp1[slice].data[i + 2] = imageData[slice].pixelData[i + 2];
              pixelDisp1[slice].data[i + 3] = imageData[slice].pixelData[i + 3];
            }
          }
          context1.putImageData(pixelDisp1[0], 0, 0);

          // change the width and height scale of imageData
          var dataURL1 = canvas1.toDataURL();
          var img1 = new Image();
          img1.src = dataURL1;
          canvas1.width = canvas1Width;
          canvas1.height = canvas1Height;

          /*-----------------------------------------------------------------------------------------
           * generate image in the canvas of sub2
           ------------------------------------------------------------------------------------------*/
          var canvas2 = cornerstone.getEnabledElement($('#sub' + subViewsNum.toString() + '2').get(0)).canvas;
          var canvas2Width = canvas2.width;
          var canvas2Height = canvas2.height;
          canvas2.width = height;
          canvas2.height = imageData.length;
          var context2 = canvas2.getContext('2d');
          var pixelDisp2 = new Array(imageData.length);

          // get each pixel data to be showed
          for (var slice = 0; slice < width; slice++) {
            var pixIndex = 0;
            var startIdx = slice * 4;
            var endIdx = (slice + width * (height - 1)) * 4;
            pixelDisp2[slice] = context2.createImageData(height, imageData.length);
            for (var i = 0; i < imageData.length; i++) {
              for (var j = startIdx; j <= endIdx; j += width * 4) {
                pixelDisp2[slice].data[pixIndex + 0] = imageData[i].pixelData[j + 0];
                pixelDisp2[slice].data[pixIndex + 1] = imageData[i].pixelData[j + 1];
                pixelDisp2[slice].data[pixIndex + 2] = imageData[i].pixelData[j + 2];
                pixelDisp2[slice].data[pixIndex + 3] = imageData[i].pixelData[j + 3];

                pixIndex += 4;
              }
            }
          }
          context2.putImageData(pixelDisp2[parseInt(width / 2)], 0, 0);

          // change the width and height scale of imageData
          var dataURL2 = canvas2.toDataURL();
          var img2 = new Image();
          img2.src = dataURL2;
          canvas2.width = canvas2Width;
          canvas2.height = canvas2Height;

          /*----------------------------------------------------------------------------------------
           * generate image in the canvas of sub3
           -----------------------------------------------------------------------------------------*/
          var canvas3 = cornerstone.getEnabledElement($('#sub' + subViewsNum.toString() + '3').get(0)).canvas;
          var canvas3Width = canvas3.width;
          var canvas3Height = canvas3.height;
          canvas3.width = width;
          canvas3.height = imageData.length;
          var context3 = canvas3.getContext('2d');
          var pixelDisp3 = new Array(imageData.length);

          // get each pixel data to be showed
          for (var slice = 0; slice < height; slice++) {
            var pixIndex = 0;
            var startIdx = (slice * width) * 4;
            var endIdx = ((slice + 1) * width - 1) * 4;
            pixelDisp3[slice] = context3.createImageData(width, imageData.length);
            for (var i = 0; i < imageData.length; i++) {
              for (var j = startIdx; j <= endIdx; j += 4) {
                pixelDisp3[slice].data[pixIndex + 0] = imageData[i].pixelData[j + 0];
                pixelDisp3[slice].data[pixIndex + 1] = imageData[i].pixelData[j + 1];
                pixelDisp3[slice].data[pixIndex + 2] = imageData[i].pixelData[j + 2];
                pixelDisp3[slice].data[pixIndex + 3] = imageData[i].pixelData[j + 3];

                pixIndex += 4;
              }
            }
          }
          context3.putImageData(pixelDisp3[parseInt(height / 2)], 0, 0);

          // change the width and height scale of imageData
          var dataURL3 = canvas3.toDataURL();
          var img3 = new Image();
          img3.src = dataURL3;
          canvas3.width = canvas3Width;
          canvas3.height = canvas3Height;

          // to bind the mouse wheel event
          $('#sub' + subViewsNum.toString() + '1').on('mousewheel DOMMouseScroll', mouseWheel);
          $('#sub' + subViewsNum.toString() + '2').on('mousewheel DOMMouseScroll', mouseWheel);
          $('#sub' + subViewsNum.toString() + '3').on('mousewheel DOMMouseScroll', mouseWheel);

          windowResize();
          window.addEventListener('resize', windowResize, false);

          // this function is used to adjust the table to let it fit the whole page
          function windowResize() {
            if ($('#sub' + subViewsNum.toString() + '0').get(0) == undefined) { // when this button is off
              return;
            }

            var localWidth = imageElement.width();
            var localHeight = imageElement.height();
            $('#imageContainer').parent().css('height', '100%');
            $('#imageContainer').css('height', '100%');
            $('#tableViews').css('height', '99.9%');

            for (var i = 0; i < 4; i++) {
              var imgCanvas = $('#sub' + subViewsNum.toString() + i.toString()).find('canvas');
              imgCanvas.get(0).height = Math.floor(localHeight / 2 - 6);
              imgCanvas.get(0).width = Math.floor(localWidth / 2 - 6);
              imgCanvas.css('height', Math.floor(localHeight / 2 - 6).toString() + 'px');
              imgCanvas.css('width', Math.floor(localWidth / 2 - 6).toString() + 'px');
            }

            // draw images in all sub-viewports
            drawImage0();
            drawImage1();
            drawImage2();
            drawImage3();

            $('#modalProgressGlobal').modal('hide');
          }

          // fill and fit the sub0 screen
          function drawImage0() {
            canvas0Width = canvas0.width;
            canvas0Height = canvas0.height;
            if (canvas0Height / height > canvas0Width / width) {
              context0.drawImage(img0,
                0,
                (canvas0Height - parseInt(height * canvas0Width / width)) / 2,
                canvas0Width,
                parseInt(height * canvas0Width / width));
            } else {
              context0.drawImage(img0,
                (canvas0Width - parseInt(width * canvas0Height / height)) / 2,
                0,
                parseInt(width * canvas0Height / height),
                canvas0Height);
            }
          }

          // fill and fit the sub1 screen
          var drawParameter1 = {};

          function drawImage1() {
            canvas1Width = canvas1.width;
            canvas1Height = canvas1.height;
            var draw =
            {
              startX: 0,
              startY: 0,
              width: 0,
              height: 0
            };
            if (canvas1Height / height > canvas1Width / width) {
              draw.startX = 0;
              draw.startY = (canvas1Height - parseInt(height * canvas1Width / width)) / 2;
              draw.width = canvas1Width;
              draw.height = parseInt(height * canvas1Width / width);
            } else {
              draw.startX = (canvas1Width - parseInt(width * canvas1Height / height)) / 2;
              draw.startY = 0;
              draw.width = parseInt(width * canvas1Height / height);
              draw.height = canvas1Height;
            }
            context1.drawImage(img1, draw.startX, draw.startY, draw.width, draw.height);
            drawParameter1 = draw;

            var displayText = 'Img: ' + (imgIndex1 + 1 || 1).toString() + '/' + imageData.length.toString();
            info1[0].innerHTML = displayText;
          }

          // fill and fit the sub2 screen
          var drawParameter2 = {};

          function drawImage2() {
            canvas2Width = canvas2.width;
            canvas2Height = canvas2.height;
            var draw =
            {
              startX: 0,
              startY: 0,
              width: 0,
              height: 0
            };
            if (canvas2Height / ((imageData.length) * stretchScale) > canvas2Width / width) {
              draw.startX = 0;
              draw.startY = (canvas2Height - parseInt((imageData.length) * stretchScale * canvas2Width / width)) / 2;
              draw.width = canvas2Width;
              draw.height = parseInt((imageData.length) * stretchScale * canvas2Width / width);
            } else {
              draw.startX = (canvas2Width - parseInt(width * canvas2Height / ((imageData.length) * stretchScale))) / 2;
              draw.startY = 0;
              draw.width = parseInt(width * canvas2Height / ((imageData.length) * stretchScale));
              draw.height = canvas2Height;
            }
            context2.drawImage(img2, draw.startX, draw.startY, draw.width, draw.height);
            drawParameter2 = draw; // export

            var displayText = 'Img: ' + (imgIndex2 + 1 || parseInt(width / 2) + 1).toString() + '/' + width.toString();
            info2[0].innerHTML = displayText;
          }

          // fill and fit the sub3 screen
          var drawParameter3 = {};

          function drawImage3() {
            canvas3Width = canvas3.width;
            canvas3Height = canvas3.height;
            var draw =
            {
              startX: 0,
              startY: 0,
              width: 0,
              height: 0
            };
            if (canvas3Height / ((imageData.length) * stretchScale) > canvas3Width / width) {
              draw.startX = 0;
              draw.startY = (canvas3Height - parseInt((imageData.length) * stretchScale * canvas3Width / width)) / 2;
              draw.width = canvas3Width;
              draw.height = parseInt((imageData.length) * stretchScale * canvas3Width / width);
            } else {
              draw.startX = (canvas3Width - parseInt(width * canvas3Height / ((imageData.length) * stretchScale))) / 2;
              draw.startY = 0;
              draw.width = parseInt(width * canvas3Height / ((imageData.length) * stretchScale));
              draw.height = canvas3Height;
            }
            context3.drawImage(img3, draw.startX, draw.startY, draw.width, draw.height);
            drawParameter3 = draw; // export

            var displayText = 'Img: ' + (imgIndex3 + 1 || parseInt(height / 2) + 1).toString() + '/' + height.toString();
            info3[0].innerHTML = displayText;
          }

          var imgIndex1 = 0;
          var imgIndex2 = parseInt(width / 2);
          var imgIndex3 = parseInt(height / 2);

          // mouseWheel event of "threeViewers" button
          function mouseWheel(e) {
            var element = e.currentTarget;

            if (element.id == 'sub' + subViewsNum.toString() + '1') {
              if (e.originalEvent.deltaY > 0) {
                imgIndex1++;
                imgIndex1 = imgIndex1 < imageData.length ? imgIndex1 : imageData.length - 1;
              } else if (e.originalEvent.deltaY < 0) {
                imgIndex1--;
                imgIndex1 = imgIndex1 > -1 ? imgIndex1 : 0;
              }
              // to invoke the imageData
              canvas1.width = width;
              canvas1.height = height;
              context1.putImageData(pixelDisp1[imgIndex1], 0, 0);

              //change the width and height scale of imageData
              img1.src = canvas1.toDataURL();
              canvas1.width = canvas1Width;
              canvas1.height = canvas1Height;

              //fill and fit the sub1 screen
              drawImage1();

              // draw reference line in sub2
              drawImage2();
              context2.beginPath();
              context2.moveTo(drawParameter2.startX,
                drawParameter2.startY + drawParameter2.height * (imgIndex1 + 0.5) / imageData.length);
              context2.lineTo(drawParameter2.startX + drawParameter2.width - 1,
                drawParameter2.startY + drawParameter2.height * (imgIndex1 + 0.5) / imageData.length);
              context2.strokeStyle = 'yellow';
              context2.lineWidth = 2;
              context2.stroke();

              // draw reference line in sub3
              drawImage3();
              context3.beginPath();
              context3.moveTo(drawParameter3.startX,
                drawParameter3.startY + drawParameter3.height * (imgIndex1 + 0.5) / imageData.length);
              context3.lineTo(drawParameter3.startX + drawParameter3.width - 1,
                drawParameter3.startY + drawParameter3.height * (imgIndex1 + 0.5) / imageData.length);
              context3.strokeStyle = 'yellow';
              context3.lineWidth = 2;
              context3.stroke();

            }
            if (element.id == 'sub' + subViewsNum.toString() + '2') {
              if (e.originalEvent.deltaY > 0) {
                imgIndex2++;
                imgIndex2 = imgIndex2 < width ? imgIndex2 : width - 1;
              } else if (e.originalEvent.deltaY < 0) {
                imgIndex2--;
                imgIndex2 = imgIndex2 > -1 ? imgIndex2 : 0;
              }
              // to invoke the imageData
              canvas2.width = width;
              canvas2.height = imageData.length;
              context2.putImageData(pixelDisp2[imgIndex2], 0, 0);

              // change the width and height scale of imageData
              img2.src = canvas2.toDataURL();
              canvas2.width = canvas2Width;
              canvas2.height = canvas2Height;

              // fill and fit the sub2 screen
              drawImage2();

              // draw reference line in sub1
              drawImage1();
              context1.beginPath();
              context1.moveTo(drawParameter1.startX + drawParameter1.width * (imgIndex2 + 0.5) / width,
                drawParameter1.startY);
              context1.lineTo(drawParameter1.startX + drawParameter1.width * (imgIndex2 + 0.5) / width,
                drawParameter1.startY + drawParameter1.height - 1);
              context1.strokeStyle = 'yellow';
              context1.lineWidth = 2;
              context1.stroke();

              // draw reference line in sub3
              drawImage3();
              context3.beginPath();
              context3.moveTo(drawParameter3.startX + drawParameter3.width * (imgIndex2 + 0.5) / width,
                drawParameter3.startY);
              context3.lineTo(drawParameter3.startX + drawParameter3.width * (imgIndex2 + 0.5) / height,
                drawParameter3.startY + drawParameter3.height - 1);
              context3.strokeStyle = 'yellow';
              context3.lineWidth = 2;
              context3.stroke();
            }
            if (element.id == 'sub' + subViewsNum.toString() + '3') {
              if (e.originalEvent.deltaY > 0) {
                imgIndex3++;
                imgIndex3 = imgIndex3 < height ? imgIndex3 : height - 1;
              } else if (e.originalEvent.deltaY < 0) {
                imgIndex3--;
                imgIndex3 = imgIndex3 > -1 ? imgIndex3 : 0;
              }
              // to invoke the imageData
              canvas3.width = width;
              canvas3.height = imageData.length;
              context3.putImageData(pixelDisp3[imgIndex3], 0, 0);

              // change the width and height scale of imageData
              img3.src = canvas3.toDataURL();
              canvas3.width = canvas3Width;
              canvas3.height = canvas3Height;

              // fill and fit the sub3 screen
              drawImage3();

              // draw reference line in sub1
              drawImage1();
              context1.beginPath();
              context1.moveTo(drawParameter1.startX,
                drawParameter1.startY + drawParameter1.height * (imgIndex3 + 0.5) / height);
              context1.lineTo(drawParameter1.startX + drawParameter1.width - 1,
                drawParameter1.startY + drawParameter1.height * (imgIndex3 + 0.5) / height);
              context1.strokeStyle = 'yellow';
              context1.lineWidth = 2;
              context1.stroke();

              // draw reference line in sub2
              drawImage2();
              context2.beginPath();
              context2.moveTo(drawParameter2.startX + drawParameter2.width * (imgIndex3 + 0.5) / height,
                drawParameter2.startY);
              context2.lineTo(drawParameter2.startX + drawParameter2.width * (imgIndex3 + 0.5) / height,
                drawParameter2.startY + drawParameter2.height - 1);
              context2.strokeStyle = 'yellow';
              context2.lineWidth = 2;
              context2.stroke();
            }
          }
        }
      });
    }
  };
  ui.cornerMarkClick = function () {
    /**
     * version:1.0
     * date:2016-8-12
     * auth:tangzhengxiong
     * desc:display or close the corner mark of each viewport
     *
     * */
    lmViewer.ui.recoverButtonColor();
    $('#cornerMark').css('background-color', 'gray');

    if (lmViewer.data.dis == false) {
      lmViewer.data.dis = true;
    } else {
      lmViewer.data.dis = false;
    }
    humane.log("显示/隐藏角标", {timeout: 2000});
    if (lmViewer.data.viewportNum == 0) {
      for (var i = 0; i <= lmViewer.data.sort; i++) {
        $("#mrtopright" + i).toggle();
        $("#mrbottomright" + i).toggle();
        $("#mrbottomleft" + i).toggle();
      }
    } else {
      for (var i = 0; i <= lmViewer.data.viewportNum; i++) {
        $("#mrtopright" + i).toggle();
        $("#mrbottomright" + i).toggle();
        $("#mrbottomleft" + i).toggle();
      }
    }
  };
  ui.resetWWWLClick = function () {
    /**
     * version:1.0
     * date:2016-8-12
     * auth:tangzhengxiong
     * desc:recover the window level and window width when modified by the five buttons on the left
     *
     * */
    humane.log("重置 窗宽/窗位", {timeout: 2000});
    recoverButtonColor();
    $('#resetWWWL').css('background-color', 'gray');
    $('#imageContainer').removeClass('adjust');

    if (lmViewer.data.contrastButtonPressed == false) {
      return;
    }
    for (var i = 0; i < lmViewer.data.iWindowHNum; i++) {
      for (var j = 0; j < lmViewer.data.iWindowVNum; j++) {
        var element = $('#image' + i.toString() + j.toString()).get(0);
        var curElement = cornerstone.getEnabledElement(element);

        var eleIndex = 0;
        if ('' != lmViewer.data.sort && 1 == lmViewer.data.iWindowVNum && 1 == lmViewer.data.iWindowHNum) {
          eleIndex = parseInt(lmViewer.data.sort);
        } else {
          eleIndex = i * lmViewer.data.iWindowVNum + j;
        }

        if (eleIndex <= lmViewer.data.viewportNum || lmViewer.data.iWindowVNum * lmViewer.data.iWindowHNum == 1) {
          var eleImgIndex = 0;
          if (lmViewer.data.iWindowHNum * lmViewer.data.iWindowVNum == 1) {
            eleImgIndex = lmViewer.data.sort;
          } else {
            eleImgIndex = lmViewer.data.loadedIndex[eleIndex] == -1 ? eleIndex : lmViewer.data.loadedIndex[eleIndex];
          }
          var curImageIDs = [];
          var _obj = {
            series: lmViewer.data.seriesArray[eleImgIndex],
            imagesid: curImageIDs
          };
          lmViewer.fn.loadImages(_obj);
          // loadImages(lmViewer.data.hosturl, lmViewer.data.serverURL, lmViewer.data.queryParams.studyUID, lmViewer.data.seriesArray[eleImgIndex], curImageIDs,lmViewer.data.queryParams.imageType);

          var _data = {
            element: element,
            image: undefined
          };
          var instanceNum = lmViewer.fn.getImgIndex(_data).instance;
          curImageIDs[instanceNum] = curImageIDs[instanceNum] +
            '&windowWidth=' + lmViewer.data.initialWW[eleIndex].toString() +
            '&windowCenter=' + lmViewer.data.initialWL[eleIndex].toString();
          cornerstone.loadAndCacheImage(curImageIDs[instanceNum]).then(function (image) {
            cornerstone.displayImage(element, image);
            var viewport = curElement.viewport;
            viewport.voi.windowCenter = image.windowCenter;
            viewport.voi.windowWidth = image.windowWidth;
            cornerstone.setViewport(element, viewport);
            lmViewer.fn.triggerResize();
          });

          lmViewer.data.globalWW[eleIndex] = lmViewer.data.initialWW[eleIndex];
          lmViewer.data.globalWL[eleIndex] = lmViewer.data.initialWL[eleIndex];
        }
      }
    }

    cornerstoneTools.wwwc.deactivate(element, 1);
  };
  ui.synchronizerClick = function () {

    /**
     * version:1.0
     * date:2016-8-12
     * auth:tangzhengxiong
     * desc:build/remove the connection of synchronizers
     *
     * */
    humane.log("建立/解除 序列关联");
    lmViewer.ui.recoverButtonColor();
    $('#synchronizer').css('background-color', 'gray');

    if (lmViewer.data.synchrSwitch) {
      lmViewer.data.synchrSwitch = false;
      $("#synchronizer span").removeClass("hy-jiesuo").addClass("hy-suoding").css("color", "#38c500");
    } else {
      lmViewer.data.synchrSwitch = true;
      $("#synchronizer span").removeClass("hy-suoding").addClass("hy-jiesuo").css("color", "#505050");
    }
  };
  ui.referenceLineClick = function () {
    /**
     * version:1.0
     * date:2016-8-12
     * auth:tangzhengxiong
     * desc:recover the window level and window width when modified by the five buttons on the left
     *
     * */
    humane.log("点击某一子窗口 开启/关闭定位线");
    lmViewer.ui.recoverButtonColor();
    $('#referenceLine').css('background-color', 'gray');
    // 如果是关闭此按钮，则刷新所有图像后退出，否则继续执行后续代码
    if (lmViewer.data.referenceLineButtonPressed === false) {
      lmViewer.data.referenceLineButtonPressed = true;
    } else {
      lmViewer.data.referenceLineButtonPressed = false;
      lmViewer.fn.updateAllImageDisplayed();
      return;
    }

    // 这一段是复制的“synchronizer”里面的代码，目的是关闭关联
    for (var i = 0; i < lmViewer.data.iWindowHNum; i++) {
      for (var j = 0; j < lmViewer.data.iWindowVNum; j++) {
        if (i * lmViewer.data.iWindowVNum + j >= lmViewer.data.loadedIndex.length) {
          break;
        }
        var curElement = $('#image' + i.toString() + j.toString()).get(0);
        var curSeriesIndex = lmViewer.data.loadedIndex[i * lmViewer.data.iWindowVNum + j] == -1 ? i * lmViewer.data.iWindowVNum + j : lmViewer.data.loadedIndex[i * lmViewer.data.iWindowVNum + j];
        var curGroupIndex = lmViewer.data.groupIndex[curSeriesIndex];

        lmViewer.data.synchronizers[curGroupIndex].remove(curElement);
      }
    }
    lmViewer.data.synchrSwitch = false;

    var element = lmViewer.data.elementChoosed == '' ? $('#image00').get(0) : lmViewer.data.elementChoosed;
    var _drawReferenceLineObj = {
      element: element
    };
    lmViewer.fn.drawReferenceLine(element);
  };
  ui.resizeCanvas = function () {
    $('#content').css('marginTop', ($('.navbar-static-top').height() + $('#tabs1').height() + $('.nav-tabs').height()).toString() + 'px');//设置影像框距离距离顶部距离
    $('#liViewer').css('marginLeft', ((document.body.clientWidth - $('#toolbar-function').width()) / 2).toString() + 'px');//设置工具栏的位置
    if (lmViewer.data.series[0].modality != "CT") {
      $('#toolBar').css('display', 'none');
    }
    $('#slice-range').css('display', 'none');
    var seriesDivHeight = $('#content').height();
    var clientWidth = document.body.clientWidth;
    var clientHeight = document.body.clientHeight;

    if (clientWidth > clientHeight) {
      $('#vertical').css('display', 'block');
      $('#transverse').css('display', 'none');
      $(' #contentDiv').parent().css('position', 'absolute');
      $(' #contentDiv').parent().css('left', '');
      // var width = (document.body.clientWidth - $('#series').width() - $('.sidebar-collapse').width()).toString() + 'px';
      // $(' #contentDiv').parent().css('width', width.toString());
    } else {
      $('#vertical').css('display', 'none');
      $('#transverse').css('display', 'block');
      $('#contentDiv').parent().css('position', "");
      // var width = (document.body.clientWidth - $('#series').width() - $('.sidebar-collapse').width()).toString() + 'px';
      // $(' #contentDiv').parent().css('width', width.toString());
    }

    var cnt = parseInt('0');
    //todo 横竖屏切换
    // if (clientWidth > clientHeight) {
    //     document.getElementById("imageContainer").style.width =
    //         (document.body.clientWidth - $('#series').width() - $('.sidebar-collapse').width()).toString() + 'px';
    //     // console.log(document.getElementById("imageContainer").style.width);
    // } else {
    //     document.getElementById("imageContainer").style.width =
    //         document.body.clientWidth.toString() + 'px';
    //     // console.log(document.getElementById("imageContainer").style.width);
    // }
    /**
     * 用于当左侧框收缩或展开时控制右侧影像向左或向右移动，但宽度没有调整；
     *
     */
    $('#content').css('left', '150px');
    if ($('#side-menu').attr('style') && lmViewer.data.windowWidth == document.body.clientWidth && lmViewer.data.windowHeight == document.body.clientHeight) {
      if (clientWidth > clientHeight) {
        document.getElementById("imageContainer").style.width =
          (document.body.clientWidth - $('#series').width() - $('.sidebar-collapse').width() - 150).toString() + 'px';
      }
    }

    /**
     * 计算“影像”，“数量”的高度
     */
    // $('#series').css('height',(document.body.clientHeight - $('.navbar-static-top').height() - $('#tabs1').height() - $('.nav-tabs').height()).toString() + 'px');
    // $('#content').css('height',(document.body.clientHeight - $('.navbar-static-top').height() - $('#tabs1').height() - $('.nav-tabs').height()).toString() + 'px');

    for (var x = 0; x < lmViewer.data.iWindowHNum; x++) {
      for (var y = 0; y < lmViewer.data.iWindowVNum; y++) {

        var imageDivId = "image" + x.toString() + y.toString();
        var element = $('#' + imageDivId).get(0);

        if (element === undefined) {
          continue;
        }

        var enabledElement = cornerstone.getEnabledElement(element);
        var currCanvas = enabledElement.canvas.getContext('2d').canvas;
        // var totalWidth = $('#imageContainer').width();
        // var totalWidth = document.body.clientWidth - $('#series').width() - $('.sidebar-collapse').width();
        var totalWidth = $("#imageContainer").parent().width();
        var totalHeight = $("#imageContainer").parent().height() - 8;

        //通俗点说就是在canvas中定义width、height跟在style中定义width和height是不同的，canvas标签的width和height是画布实际宽度和高度，绘制的图形都是在这个上面。而style的width和height是canvas在浏览器中被渲染的高度和宽度。如果canvas的width和height没指定或值不正确，就被设置成默认值(width:300px，height:150px)。
        currCanvas.width = Math.floor(totalWidth / lmViewer.data.iWindowVNum) - 2;//减去左右的border

        currCanvas.height = Math.floor(totalHeight / lmViewer.data.iWindowHNum);
        var iWidth = Math.floor(totalWidth / lmViewer.data.iWindowVNum) - 2;//减去左右的border
        var iHeight = Math.floor(totalHeight / lmViewer.data.iWindowHNum);
        currCanvas.style.width = iWidth.toString() + 'px';
        currCanvas.style.height = iHeight.toString() + 'px';

        //todo tangzhengxiong 2016/9/25
        // cornerstone.fitToWindow(element);
        //todo tangzhengxiong 2016/9/23
        lmViewer.fn.RT.setScale(element);
        if (lmViewer.data.isDesktop && lmViewer.data.queryParams.imageType == "dicom") {
          var _plottingScaleObj = {
            element: element
          };
          lmViewer.fn.plottingScale(_plottingScaleObj);
        }

        // PC浏览器为竖屏时样式调整
        if (lmViewer.data.isDesktop && clientWidth < clientHeight) {
          var contentHeight = window.innerHeight - $('#navbar').height() - $('#tabs1').height() - 15;
          var imageContainerHeight = contentHeight - $('#series_transverse').height() - 10;
          $(' #contentDiv').parent().css('width', '100%');
          $(' #contentDiv').parent().css('height', contentHeight.toString());

          $(' #imageContainer').css('width', '100%');
          $(' #imageContainer').css('height', imageContainerHeight.toString());

          $(' #' + imageDivId).parent().css('width', '100%');
          $(' #' + imageDivId).parent().css('height', (imageContainerHeight / lmViewer.data.iWindowHNum - 2 * lmViewer.data.iWindowHNum).toString());

          $(' #' + imageDivId).find('canvas')[0].width = ($(' #imageContainer').width() - 4) / lmViewer.data.iWindowVNum;
          $(' #' + imageDivId).find('canvas')[0].height = imageContainerHeight / lmViewer.data.iWindowHNum - 4 * lmViewer.data.iWindowHNum - 4;
          $(' #' + imageDivId).find('canvas')[0].style.width = (($(' #imageContainer').width() - 4) / lmViewer.data.iWindowVNum) + 'px';
          $(' #' + imageDivId).find('canvas')[0].style.height = (imageContainerHeight / lmViewer.data.iWindowHNum - 4 * lmViewer.data.iWindowHNum - 4) + 'px';

          $('#series_transverse').css('width', $(' #imageContainer').width().toString());

          // 刷新影像
          cornerstone.updateImage($('#' + imageDivId).get(0));
        }
        ;
        cnt++;
      }
    }

  };
  ui.resizeSeriesDiv = function () {
    /**
     * version:1.0
     * date:2016-8-12
     * auth:tangzhengxiong
     * desc:重新设置series的高度和宽度
     *
     * */
    var seriesDivHeight = $('#imageContainer').height();
    var seriesDivWidth = $('#imageContainer').width();
    var clientWidth = document.body.clientWidth;
    var clientHeight = document.body.clientHeight;
    if (clientWidth > clientHeight) {
      $('#series').css("height", seriesDivHeight.toString() + 'px');
    } else {
      $('#seriesList').css("width", seriesDivWidth.toString() + 'px');
    }
  };
  ui.showCurrentSeries = function (element, index) {
    lmViewer.data.elementChoosed = element;
    // if the "referenceLine" button is on, draw the reference lines on each viewport
    if (lmViewer.data.referenceLineButtonPressed === true) {
      lmViewer.fn.updateAllImageDisplayed();
      var _drawReferenceLineObj = {
        element: element
      };
      lmViewer.fn.drawReferenceLine(element);
    }

    // show the element in current viewport which is chosen with a green border
    var _selectedViewportMarkedObj = {
      element: lmViewer.data.elementChoosed
    };
    lmViewer.ui.selectedViewportMarked(_selectedViewportMarkedObj);
    if (lmViewer.data.clickedSeries === -1 || lmViewer.data.loadedIndex[index] === lmViewer.data.clickedSeries || lmViewer.data.changgeSeriesByIndex === -1) {
      return;
    }

    if (lmViewer.data.loadedIndex[index] != lmViewer.data.clickedSeries) {
      lmViewer.data.wheelInstanceNum[index] = 0;
    }
    lmViewer.data.loadedIndex[index] = lmViewer.data.clickedSeries;

    var curImageIDs = [];
    // load images 找到序列中的所有影像
    /*                if(lmViewer.data.getDicomButtonPressed){
     lmViewer.fn.loadImages(lmViewer.data.seriesArray[lmViewer.data.changgeSeriesByIndex], curImageIDs);
     /*      } else {*!/
     lmViewer.fn.loadImages(lmViewer.data.seriesArray[lmViewer.data.changgeSeriesByIndex], curImageIDs);
     // }*/
    var _obj = {
      series: lmViewer.data.seriesArray[eleImgIndex],
      imagesid: curImageIDs
    };
    lmViewer.fn.loadImages(_obj);
    /*if(lmViewer.data.getDicomButtonPressed){
     lmViewer.fn.loadImages(_obj);
     loadImages(lmViewer.data.hosturl, lmViewer.data.serverURL, lmViewer.data.queryParams.studyUID, lmViewer.data.seriesArray[lmViewer.data.changgeSeriesByIndex], curImageIDs,
     'dicom');
     } else {
     loadImages(lmViewer.data.hosturl, lmViewer.data.serverURL, lmViewer.data.queryParams.studyUID, lmViewer.data.seriesArray[lmViewer.data.changgeSeriesByIndex], curImageIDs,
     lmViewer.data.queryParams.imageType);
     }*/
    var stack = {
      currentImageIdIndex: 0,
      imageIds: curImageIDs
    };

    /*                $('#modalProgressGlobal').modal('show');*/

    cornerstone
      .loadAndCacheImage(curImageIDs[0])
      .then(
        function (image) {

          // 开启鼠标操作的功能
          if (lmViewer.data.isDesktop === true) {
            // 鼠标按下去滑动时间
            cornerstoneTools.mouseInput.enable(element);
          }

          // 开启手机的手势操作功能
          if (lmViewer.data.isMobile === true) {
            cornerstoneTools.touchInput.enable(element);
          }

          // display this image
          cornerstone.displayImage(element, image);

          // set the stack as tool state
          cornerstoneTools.addStackStateManager(element, ['stack']);
          cornerstoneTools.addToolState(element, 'stack', stack);

          if (lmViewer.data.isDesktop === true) {
            //				cornerstoneTools.wwwc.activate(element, 1); // ww/wc
            cornerstoneTools.pan.activate(element, 2); // pan
            cornerstoneTools.zoom.activate(element, 4); // zoom
          }

          if (lmViewer.data.isMobile === true) {
            cornerstoneTools.stackScrollTouchDrag.activate(element);
          }

          // add synchronizer
          var curGroupIndex = lmViewer.data.groupIndex[index];
          lmViewer.data.synchronizers[curGroupIndex].remove(element);
          curGroupIndex = lmViewer.data.groupIndex[lmViewer.data.clickedSeries];
          lmViewer.data.synchronizers[curGroupIndex].add(element);
          lmViewer.data.groupIndex[index] = lmViewer.data.groupIndex[lmViewer.data.clickedSeries];

          lmViewer.fn.triggerResize();
          var _getDicomObj = {
            element: element
          };
          var newImageId = getDicom(_getDicomObj);
          cornerstone.loadAndCacheImage(newImageId).then(function (image) {

            lmViewer.data.globalWL[index] = image.windowCenter;
            lmViewer.data.globalWW[index] = image.windowWidth;
            lmViewer.data.initialWL[index] = lmViewer.data.globalWL[index];
            lmViewer.data.initialWW[index] = lmViewer.data.globalWW[index];

            if (lmViewer.data.contrastButtonPressed) {
              cornerstone.displayImage(element, image);
              var viewport = cornerstone.getEnabledElement(element).viewport;
              viewport.voi.windowCenter = image.windowCenter;
              viewport.voi.windowWidth = image.windowWidth;
              cornerstone.setViewport(element, viewport);
              lmViewer.fn.triggerResize();
            }
          });
        });

    // TODO
    var displayText = lmViewer.data.imageInfo.patientname + (lmViewer.data.imageInfo.patientname != "" ? '<br/>' : "")
      + lmViewer.data.imageInfo.patientid + (lmViewer.data.imageInfo.patientid != "" ? '<br/>' : "");
    if (lmViewer.data.imageInfo.sex == 0) {
      displayText += 'M' + '<br/>';
    } else {
      displayText += 'F' + '<br/>';
    }
    displayText += lmViewer.data.imageInfo.institutionname + (lmViewer.data.imageInfo.institutionname != "" ? '<br/>' : "")
      + lmViewer.data.imageInfo.studydescription + (lmViewer.data.imageInfo.studydescription != "" ? '<br/>' : "")
      + lmViewer.data.series[lmViewer.data.changgeSeriesByIndex].seriesDescription + (lmViewer.data.series[lmViewer.data.changgeSeriesByIndex].seriesDescription != "" ? '<br/>' : "")
      + (lmViewer.data.imageInfo.birthday != "" ? '出生日期：' : "") + lmViewer.data.imageInfo.birthday + (lmViewer.data.imageInfo.birthday != "" ? '<br/>' : "")
      + (lmViewer.data.imageInfo.studydate != "" ? '拍摄日期：：' : "") + lmViewer.data.imageInfo.studydate;
    $('#mrbottomright' + index).html(displayText);
    // TODO

    var viewport = cornerstone.getViewport(element);
    // traverse the current series for the current instance ----------------------------------------- started by TanQilu
    var instanceNum;
    for (var i = 0; i < curImageIDs.length; i++) {
      var startIndex = curImageIDs[i].indexOf('object') + 7;
      var endIndex = curImageIDs[i].indexOf('&rows');
      if (curImageIDs[i].substring(startIndex, endIndex) == lmViewer.data.seriesArray[lmViewer.data.clickedSeries].instance[i].sopIUID) {
        instanceNum = lmViewer.data.seriesArray[lmViewer.data.clickedSeries].instance[i].instanceNumber;
        break;
      }
    }
    // ------------------------------------------------------------------------------------------------- ended by TanQilu

    var displayTextL = 'Img：' + (instanceNum + 1) + '/'
      + lmViewer.data.series[lmViewer.data.changgeSeriesByIndex].numberOfInstances + '<br/>' + 'WW：'
      + Math.round(viewport.voi.windowWidth) + '&nbsp&nbsp'
      + 'WL：' + Math.round(viewport.voi.windowCenter) + '<br/>'
      + 'Zoom：' + viewport.scale.toFixed(2) + '<br/>Loc：' + parseFloat(lmViewer.data.locations[lmViewer.data.changgeSeriesByIndex]).toFixed(2)
      + '<br/>Thick：' + parseFloat(lmViewer.data.thickness[lmViewer.data.changgeSeriesByIndex]).toFixed(2);

    $('#mrbottomleft' + index).html(displayTextL);

    lmViewer.data.changgeSeriesByIndex = -1;
  };

  ui.showEachSeries = function (obj) {
    //imageDivId, cnt
    // 设置图片显示位置区域
    lmViewer.data.wheelInstanceNum[obj.cnt] = 0;
    var mydiv = $('#' + obj.imageDivId);

    // Bottom Right
    var divBottomRight = $('<div></div>');
    divBottomRight.attr('id', 'mrbottomright' + obj.cnt);
    divBottomRight.attr('style', 'position: absolute; bottom: 6px; right:10px; text-align:right; color: white;');
    divBottomRight.appendTo(mydiv);

    var displayText = lmViewer.data.imageInfo.patientname + (lmViewer.data.imageInfo.patientname != "" ? '<br/>' : "")
      + lmViewer.data.imageInfo.patientid + (lmViewer.data.imageInfo.patientid != "" ? '<br/>' : "");
    if (lmViewer.data.imageInfo.sex == 0) {
      displayText += 'M' + '<br/>';
    } else {
      displayText += 'F' + '<br/>';
    }
    displayText += lmViewer.data.imageInfo.institutionname + (lmViewer.data.imageInfo.institutionname != "" ? '<br/>' : "")
      + lmViewer.data.imageInfo.studydescription.substring(18) + (lmViewer.data.imageInfo.studydescription != "" ? '<br/>' : "")
      + lmViewer.data.series[obj.cnt].seriesDescription + (lmViewer.data.series[obj.cnt].seriesDescription != "" ? '<br/>' : "")
      + (lmViewer.data.imageInfo.birthday != "" ? '出生日期：' : "") + lmViewer.data.imageInfo.birthday + (lmViewer.data.imageInfo.birthday != "" ? '<br/>' : "")
      + (lmViewer.data.imageInfo.studydate != "" ? '拍摄日期：' : "") + lmViewer.data.imageInfo.studydate;
    $('#mrbottomright' + obj.cnt).html(displayText);

    // Top Right
    var divTopRight = $('<div></div>');
    divTopRight.attr('id', 'mrtopright' + obj.cnt);
    divTopRight.attr('style', 'position: absolute; top: 6px; right: 6px;  color: white; border');
    divTopRight.appendTo(mydiv);
    $('#mrtopright' + obj.cnt).html('');

    // Bottom Left
    var divBottomLeft = $('<div></div>');
    divBottomLeft.attr('id', 'mrbottomleft' + obj.cnt);
    divBottomLeft.attr('style', 'position: absolute; bottom: 6px; left: 6px;  color: white;');
    divBottomLeft.appendTo(mydiv);

    // Next four divs are used to display image orientation
    // Left
    var divLeft = $('<div></div>');
    divLeft.attr('id', 'mrdivLeft' + obj.cnt);
    divLeft.attr('style', 'position: absolute; top: 0px; left: 20px; color: yellow;');
    divLeft.appendTo(mydiv);

    // Right
    var divRight = $('<div></div>');
    divRight.attr('id', 'mrdivRight' + obj.cnt);
    divRight.attr('style', 'position: absolute; top: 0px; right: 20px; color: yellow;');
    divRight.appendTo(mydiv);

    // Top
    var divTop = $('<div></div>');
    divTop.attr('id', 'mrdivTop' + obj.cnt);
    divTop.attr('style', 'position: absolute; top: 10px; left: 0px; color: yellow;');
    divTop.appendTo(mydiv);

    // Bottom
    var divBottom = $('<div></div>');
    divBottom.attr('id', 'mrdivBottom' + obj.cnt);
    divBottom.attr('style', 'position: absolute; bottom: 20px; left: 0px; color: yellow;');
    divBottom.appendTo(mydiv);

    // For input and view
    function onViewportUpdated(e, data) {
      var div = e.currentTarget;
      var enabledElement = cornerstone.getEnabledElement(div);
      var viewport = enabledElement.viewport;
      var displayText;
      var instanceNum; // instance number displayed before the symbol "/", added by TanQilu
      var imageTotalNum; // total image number displayed after the symbol "/", added by TanQilu
      var curIndex = lmViewer.data.loadedIndex[obj.cnt] == -1 ? obj.cnt : lmViewer.data.loadedIndex[obj.cnt];
      // traverse the current or all series for the current instance ----------------------------------------- started by TanQilu
      for (var i = 0; i < lmViewer.data.seriesArray[curIndex].instance.length; i++) {
        var startIndex = enabledElement.image.imageId.indexOf('object') + 7;
        var endIndex = enabledElement.image.imageId.indexOf('&rows');
        if (enabledElement.image.imageId.substring(startIndex, endIndex) == lmViewer.data.seriesArray[curIndex].instance[i].sopIUID) {
          instanceNum = lmViewer.data.seriesArray[curIndex].instance[i].instanceNumber;
          imageTotalNum = lmViewer.data.seriesArray[curIndex].instance.length;
          break;
        }
      }
      if (instanceNum == undefined) {
        var hIndex = parseInt(obj.cnt / lmViewer.data.iWindowVNum);
        var vIndex = obj.cnt - parseInt(obj.cnt / lmViewer.data.iWindowVNum) * lmViewer.data.iWindowVNum;
        var curDiv = $('#image' + hIndex.toString() + vIndex.toString()).get(0);
        var curElement;
        try {
          curElement = cornerstone.getEnabledElement(curDiv);
        } catch (another) {
          curElement = cornerstone.getEnabledElement(div);
        }

        for (var i = 0; i < lmViewer.data.seriesArray[curIndex].instance.length; i++) {
          var startIndex = curElement.image.imageId.indexOf('object') + 7;
          var endIndex = curElement.image.imageId.indexOf('&rows');
          if (curElement.image.imageId.substring(startIndex, endIndex) == lmViewer.data.seriesArray[curIndex].instance[i].sopIUID) {
            instanceNum = lmViewer.data.seriesArray[curIndex].instance[i].instanceNumber;
            imageTotalNum = lmViewer.data.seriesArray[curIndex].instance.length;
            break;
          }
        }
      }
      // --------------------------------------------------------------------------------------------------------- ended by TanQilu
      lmViewer.data.curImageNum = instanceNum; // export current variable to global variable
      if (lmViewer.data.initialWW[curIndex] == undefined || lmViewer.data.initialWL[curIndex] == undefined) {
        lmViewer.data.initialWW[curIndex] = viewport.voi.windowWidth;
        lmViewer.data.initialWL[curIndex] = viewport.voi.windowCenter;
      }

      displayText = 'Img：' + (instanceNum + 1) + '/'
        + (imageTotalNum) + '<br/>' + 'WW：'
        + Math.ceil(viewport.voi.windowWidth) + '&nbsp&nbsp'
        + 'WL：' + Math.ceil(viewport.voi.windowCenter) + '<br/>'
        + 'Zoom：' + viewport.scale.toFixed(2);
      $('#mrbottomleft' + obj.cnt).html(displayText);

      // to mark the viewport which is selected
      var curElementId = div.id;
      $('#' + curElementId).css('border', '1px solid #454444');
      $('#' + curElementId).css('border-color', '#000');
      var _selectedViewportMarkedObj = {
        element: lmViewer.data.elementChoosed
      };
      lmViewer.ui.selectedViewportMarked(_selectedViewportMarkedObj);
      if (lmViewer.data.isDesktop) {
        var _plottingScaleObj = {
          element: div
        };
        lmViewer.fn.plottingScale(_plottingScaleObj);

        // display the image orientation
        divLeft.get(0).style.top = ($('#' + div.id).height() / 2).toString() + 'px';
        divRight.get(0).style.top = ($('#' + div.id).height() / 2).toString() + 'px';
        divTop.get(0).style.left = ($('#' + div.id).width() / 2).toString() + 'px';
        divBottom.get(0).style.left = ($('#' + div.id).width() / 2).toString() + 'px';

        // get the series number and instance number

        var _obj = {
          element: div,
          image: undefined
        };
        var imgIndex = lmViewer.fn.getImgIndex(_obj);
        // get the series number and instance number
        var instanceNum = imgIndex.instance;
        var seriesNum = imgIndex.series;
        if (lmViewer.data.tagArray[seriesNum][instanceNum].imageOrientation == undefined) {
          return;
        }

        var Xx = parseFloat(lmViewer.data.tagArray[seriesNum][instanceNum].imageOrientation.split('\\')[0]);
        var Xy = parseFloat(lmViewer.data.tagArray[seriesNum][instanceNum].imageOrientation.split('\\')[1]);
        var Xz = parseFloat(lmViewer.data.tagArray[seriesNum][instanceNum].imageOrientation.split('\\')[2]);
        var Yx = parseFloat(lmViewer.data.tagArray[seriesNum][instanceNum].imageOrientation.split('\\')[3]);
        var Yy = parseFloat(lmViewer.data.tagArray[seriesNum][instanceNum].imageOrientation.split('\\')[4]);
        var Yz = parseFloat(lmViewer.data.tagArray[seriesNum][instanceNum].imageOrientation.split('\\')[5]);

        var leftDisp = '';
        var rightDisp = '';
        var topDisp = '';
        var bottomDisp = '';
        // Xx
        if (Xx > 0.1) {
          leftDisp += 'R';
          rightDisp += 'L';
        } else if (Xx < -0.1) {
          leftDisp += 'L';
          rightDisp += 'R';
        }
        // Xy
        if (Xy > 0.1) {
          leftDisp += 'A';
          rightDisp += 'P';
        } else if (Xy < -0.1) {
          leftDisp += 'P';
          rightDisp += 'A';
        }
        // Xz
        if (Xz > 0.1) {
          leftDisp += 'I';
          rightDisp += 'S';
        } else if (Xz < -0.1) {
          leftDisp += 'S';
          rightDisp += 'I';
        }
        //Yx
        if (Yx > 0.1) {
          topDisp += 'R';
          bottomDisp += 'L';
        } else if (Yx < -0.1) {
          topDisp += 'L';
          bottomDisp += 'R';
        }
        //Yy
        if (Yy > 0.1) {
          topDisp += 'A';
          bottomDisp += 'P';
        } else if (Yy < -0.1) {
          topDisp += 'P';
          bottomDisp += 'A';
        }
        //Yz
        if (Yz > 0.1) {
          topDisp += 'I';
          bottomDisp += 'S';
        } else if (Yz < -0.1) {
          topDisp += 'S';
          bottomDisp += 'I';
        }

        divLeft.html(leftDisp);
        divRight.html(rightDisp);
        divTop.html(topDisp);
        divBottom.html(bottomDisp);
      }
    };

    var element = $('#' + obj.imageDivId).get(0);

    // image enable the dicomImage element and the mouse inputs
    cornerstone.enable(element);

    var imageIDs = [];
    // load images 找到序列中的所有影像
    var _obj = {
      series: lmViewer.data.seriesArray[obj.cnt],
      imagesid: imageIDs
    };
    lmViewer.fn.loadImages(_obj);
    /*  lmViewer.fn.loadImages(lmViewer.data.hosturl, lmViewer.data.serverURL, lmViewer.data.queryParams.studyUID, lmViewer.data.seriesArray[cnt], imageIDs,
     lmViewer.data.queryParams.imageType);*/
    var stack = {
      currentImageIdIndex: 0,
      imageIds: imageIDs
    };

    // Bind hotkeys
    jQuery(document).bind('keydown.1', function (evt) {
      lmViewer.datacontrastButtonPressed = true;
      var _getDicomObj = {
        element: element
      };
      var newImageId = getDicom(element);

      cornerstone.loadAndCacheImage(newImageId).then(function (image) {
        cornerstone.displayImage(element, image);
        var viewport = cornerstone.getEnabledElement(element).viewport;
        var _obj = {
          element: element,
          image: undefined
        };
        var seriesNum = lmViewer.fn.getImgIndex(_obj).series;
        lmViewer.data.initialWL[seriesNum] = image.windowCenter;
        lmViewer.data.initialWW[seriesNum] = image.windowWidth;

        viewport.voi.windowCenter = 35;
        viewport.voi.windowWidth = 80;

        // element 的行列索引
        var eleRowIndex = element.id.substring(
          element.id.indexOf('image') + 5,
          element.id.indexOf('image') + 6);
        var eleColumnIndex = element.id.substring(
          element.id.indexOf('image') + 6);
        eleRowIndex = parseInt(eleRowIndex);
        eleColumnIndex = parseInt(eleColumnIndex);

        var elementIdx = 0;
        if ('' != lmViewer.data.sort && 1 == lmViewer.data.iWindowVNum && 1 == lmViewer.data.iWindowHNum) {
          elementIdx = parseInt(lmViewer.data.sort);
        } else {
          elementIdx = eleRowIndex * lmViewer.data.iWindowVNum + eleColumnIndex;
        }

        lmViewer.data.globalWL[elementIdx] = 35;
        lmViewer.data.globalWW[elementIdx] = 80;

        cornerstone.setViewport(element, viewport);
        lmViewer.fn.triggerResize();
      });

      cornerstoneTools.wwwc.activate(element, 1);
    });

    jQuery(document).bind('keydown.2', function (evt) {
      $('#modalProgressGlobal').modal('show');
      lmViewer.data.contrastButtonPressed = true;
      var _getDicomObj = {
        element: element
      };
      var newImageId = getDicom(_getDicomObj);

      cornerstone.loadAndCacheImage(newImageId).then(function (image) {
        cornerstone.displayImage(element, image);
        var viewport = cornerstone.getEnabledElement(element).viewport;
        var _obj = {
          element: element,
          image: undefined
        };
        var seriesNum = lmViewer.fn.getImgIndex(_obj).series;
        lmViewer.data.initialWL[seriesNum] = image.windowCenter;
        lmViewer.data.initialWW[seriesNum] = image.windowWidth;

        viewport.voi.windowCenter = -500;
        viewport.voi.windowWidth = 1500;

        // element 的行列索引
        var eleRowIndex = element.id.substring(
          element.id.indexOf('image') + 5,
          element.id.indexOf('image') + 6);
        var eleColumnIndex = element.id.substring(
          element.id.indexOf('image') + 6);
        eleRowIndex = parseInt(eleRowIndex);
        eleColumnIndex = parseInt(eleColumnIndex);

        var elementIdx = 0;
        if ('' != lmViewer.data.sort && 1 == lmViewer.data.iWindowVNum && 1 == viWindowHNum) {
          elementIdx = parseInt(lmViewer.data.sort);
        } else {
          elementIdx = eleRowIndex * lmViewer.data.iWindowVNum + eleColumnIndex;
        }

        lmViewer.data.globalWL[elementIdx] = -500;
        lmViewer.data.globalWW[elementIdx] = 1500;

        cornerstone.setViewport(element, viewport);
        lmViewer.fn.triggerResize();
        $('#modalProgressGlobal').modal('hide');
      });

      cornerstoneTools.wwwc.activate(element, 1);
    });

    jQuery(document).bind('keydown.3', function (evt) {
      $('#modalProgressGlobal').modal('show');
      lmViewer.data.contrastButtonPressed = true;
      var _getDicomObj = {
        element: element
      };
      var newImageId = getDicom(_getDicomObj);

      cornerstone.loadAndCacheImage(newImageId).then(function (image) {
        cornerstone.displayImage(element, image);
        var viewport = cornerstone.getEnabledElement(element).viewport;
        var _obj = {
          element: element,
          image: undefined
        };
        var seriesNum = lmViewer.fn.getImgIndex(_obj).series;
        lmViewer.data.initialWL[seriesNum] = image.windowCenter;
        lmViewer.data.initialWW[seriesNum] = image.windowWidth;

        viewport.voi.windowCenter = 50;
        viewport.voi.windowWidth = 500;

        // element 的行列索引
        var eleRowIndex = element.id.substring(
          element.id.indexOf('image') + 5,
          element.id.indexOf('image') + 6);
        var eleColumnIndex = element.id.substring(
          element.id.indexOf('image') + 6);
        eleRowIndex = parseInt(eleRowIndex);
        eleColumnIndex = parseInt(eleColumnIndex);

        var elementIdx = 0;
        if ('' != lmViewer.data.sort && 1 == lmViewer.data.iWindowVNum && 1 == lmViewer.data.iWindowHNum) {
          elementIdx = parseInt(lmViewer.data.sort);
        } else {
          elementIdx = eleRowIndex * lmViewer.data.iWindowVNum + eleColumnIndex;
        }

        lmViewer.data.globalWL[elementIdx] = 50;
        lmViewer.data.globalWW[elementIdx] = 500;

        cornerstone.setViewport(element, viewport);
        lmViewer.fn.triggerResize();
        $('#modalProgressGlobal').modal('hide');
      });

      cornerstoneTools.wwwc.activate(element, 1);
    });

    jQuery(document).bind('keydown.4', function (evt) {
      lmViewer.data.contrastButtonPressed = true;
      var _getDicomObj = {
        element: element
      };
      var newImageId = getDicom(_getDicomObj);

      cornerstone.loadAndCacheImage(newImageId).then(function (image) {
        cornerstone.displayImage(element, image);
        var viewport = cornerstone.getEnabledElement(element).viewport;
        var _obj = {
          element: element,
          image: undefined
        };
        var seriesNum = lmViewer.fn.getImgIndex(_obj).series;
        lmViewer.data.initialWL[seriesNum] = image.windowCenter;
        lmViewer.data.initialWW[seriesNum] = image.windowWidth;

        viewport.voi.windowCenter = 50;
        viewport.voi.windowWidth = 350;

        // element 的行列索引
        var eleRowIndex = element.id.substring(
          element.id.indexOf('image') + 5,
          element.id.indexOf('image') + 6);
        var eleColumnIndex = element.id.substring(
          element.id.indexOf('image') + 6);
        eleRowIndex = parseInt(eleRowIndex);
        eleColumnIndex = parseInt(eleColumnIndex);

        var elementIdx = 0;
        if ('' != lmViewer.data.sort && 1 == lmViewer.data.iWindowVNum && 1 == lmViewer.data.iWindowHNum) {
          elementIdx = parseInt(lmViewer.data.sort);
        } else {
          elementIdx = eleRowIndex * lmViewer.data.iWindowVNum + eleColumnIndex;
        }

        lmViewer.data.globalWL[elementIdx] = 50;
        lmViewer.data.globalWW[elementIdx] = 350;

        cornerstone.setViewport(element, viewport);
        lmViewer.fn.triggerResize();
        $('#modalProgressGlobal').modal('hide');
      });

      cornerstoneTools.wwwc.activate(element, 1);
    });

    jQuery(document).bind('keydown.5', function (evt) {
      lmViewer.data.contrastButtonPressed = true;
      var _getDicomObj = {
        element: element
      };
      var newImageId = getDicom(_getDicomObj);

      cornerstone.loadAndCacheImage(newImageId).then(function (image) {
        cornerstone.displayImage(element, image);
        var viewport = cornerstone.getEnabledElement(element).viewport;
        var _obj = {
          element: element,
          image: undefined
        };
        var seriesNum = lmViewer.fn.getImgIndex(_obj).series;
        lmViewer.data.initialWL[seriesNum] = image.windowCenter;
        lmViewer.data.initialWW[seriesNum] = image.windowWidth;
        ;

        viewport.voi.windowCenter = 300;
        viewport.voi.windowWidth = 1500;

        // element 的行列索引
        var eleRowIndex = element.id.substring(
          element.id.indexOf('image') + 5,
          element.id.indexOf('image') + 6);
        var eleColumnIndex = element.id.substring(
          element.id.indexOf('image') + 6);
        eleRowIndex = parseInt(eleRowIndex);
        eleColumnIndex = parseInt(eleColumnIndex);

        var elementIdx = 0;
        if ('' != lmViewer.data.sort && 1 == lmViewer.data.iWindowVNum && 1 == lmViewer.data.iWindowHNum) {
          elementIdx = parseInt(lmViewer.data.sort);
        } else {
          elementIdx = eleRowIndex * lmViewer.data.iWindowVNum + eleColumnIndex;
        }

        lmViewer.data.globalWL[elementIdx] = 300;
        lmViewer.data.globalWW[elementIdx] = 1500;

        cornerstone.setViewport(element, viewport);
        lmViewer.fn.triggerResize();
      });

      cornerstoneTools.wwwc.activate(element, 1);
    });

    // this function is used in keyboard hotkeys, aiming to browse to the location of
    // an special instance --------------------------------------- Updated by TanQilu
    function hotkeyBrowse(step, key) {
      $('#imageContainer').removeClass('adjust');
      $('#enableWindowLevelTool').css('background-color', '#000');
      lmViewer.data.contrastButtonPressed = false;

      lmViewer.ui.recoverButtonColor();
      cornerstoneTools.wwwc.deactivate(element, 1);

      // get the number of the selected element
      lmViewer.data.elementChoosed = lmViewer.data.elementChoosed || $('#image00').get(0);
      var eleRowIndex = lmViewer.data.elementChoosed.id.substring(
        lmViewer.data.elementChoosed.id.indexOf('image') + 5,
        lmViewer.data.elementChoosed.id.indexOf('image') + 6);
      var eleColumnIndex = lmViewer.data.elementChoosed.id.substring(
        lmViewer.data.elementChoosed.id.indexOf('image') + 6);
      eleRowIndex = parseInt(eleRowIndex);
      eleColumnIndex = parseInt(eleColumnIndex);
      var eleIndex = eleRowIndex * lmViewer.data.iWindowVNum + eleColumnIndex;

      // get the scale of every window which will display the next image
      var enabledElement = cornerstone.getEnabledElement(lmViewer.data.elementChoosed);

      // delete the last image
      var canvas = enabledElement.canvas;
      var context = canvas.getContext('2d');
      context.clearRect(0, 0, canvas.width, canvas.height);
      context.transform(1, 0, 0, 1, 0, 0);

      context.textAlign = 'left';
      context.textBaseline = 'top';
      context.strokeStyle = '#DF5326';
      context.font = 'bold 24px arial';
      context.fillStyle = 'orange';
      //todo tangzhengxiong 2016/9/19
      //context.fillText("载入中...", canvas.width / 2 - 50, canvas.height / 2 + 12);
      //lmViewer.ui.hideDiv();
      lmViewer.ui.showLoading();
      switch (key) {
        case('left'):
        case('down'):
        case('pagedown'):
          lmViewer.data.wheelInstanceNum[eleIndex] = lmViewer.data.wheelInstanceNum[eleIndex] - step;
          break;
        case('right'):
        case('up'):
        case('pageup'):
          lmViewer.data.wheelInstanceNum[eleIndex] = lmViewer.data.wheelInstanceNum[eleIndex] + step;
          break;
        default:
      }

      // record the scale of current image
      var _obj = {
        element: lmViewer.data.elementChoosed,
        image: undefined
      };
      var imgIndex = lmViewer.fn.getImgIndex(_obj);
      var row = parseInt(lmViewer.data.tagArray[imgIndex.series][imgIndex.instance].rows);
      var rowScale = 1;
      if (cornerstone.getImage(elementChoosed).data != undefined) { // DICOM
        rowScale = row / 512;
      }
      var viewport = cornerstone.getEnabledElement(lmViewer.data.elementChoosed).viewport;
      lmViewer.data.imageScale[eleIndex] = (viewport.scale * rowScale).toFixed(2);

      var seriesIndex = lmViewer.fn.getImgIndex(_obj).series;
      var seriesNums = lmViewer.data.seriesArray[seriesIndex].instance.length;

      // show the new image with current WWWL
      if (lmViewer.data.wheelInstanceNum[eleIndex] >= seriesNums) {
        lmViewer.data.wheelInstanceNum[eleIndex] = seriesNums - 1;
      } else if (lmViewer.data.wheelInstanceNum[eleIndex] < 0) {
        lmViewer.data.wheelInstanceNum[eleIndex] = 0;
      }
      var _readjustInstanceWWWLObj = {
        index: lmViewer.data.wheelInstanceNum[eleIndex],
        element: lmViewer.data.elementChoosed
      };
      lmViewer.fn.readjustInstanceWWWL(_readjustInstanceWWWLObj);
    }

    //	jQuery(document).unbind('keydown.home');
    //	jQuery(document).bind('keydown.home', function(evt) {
    //		selectNewImage(0);
    //	});
    //
    //	jQuery(document).unbind('keydown.end');
    //	jQuery(document).bind('keydown.end', function(evt) {
    //		var sortedInstanceLength = [];
    //		for(var i = 0; i < iSeriesNum; i++){
    //			sortedInstanceLength[i] = seriesArray[i].instance.length;
    //		}
    //		sortedInstanceLength.sort(compare);
    //		for(var i = 0; i < iSeriesNum; i++){
    //			selectNewImage(sortedInstanceLength[i]-1);
    //		}
    //		function compare(value1,value2) {
    //			return value1 - value2;
    //		}
    //	});

    jQuery(document).unbind('keydown.pageup');
    jQuery(document).bind('keydown.pageup', function (evt) {
      hotkeyBrowse(10, 'pageup');
    });

    jQuery(document).unbind('keydown.pagedown');
    jQuery(document).bind('keydown.pagedown', function (evt) {
      hotkeyBrowse(10, 'pagedown');
    });

    jQuery(document).unbind('keydown.left');
    jQuery(document).bind('keydown.left', function (evt) {
      hotkeyBrowse(1, 'left');
    });

    jQuery(document).unbind('keydown.up');
    jQuery(document).bind('keydown.up', function (evt) {
      hotkeyBrowse(1, 'up');
    });

    jQuery(document).unbind('keydown.right');
    jQuery(document).bind('keydown.right', function (evt) {
      hotkeyBrowse(1, 'right');
    });

    jQuery(document).unbind('keydown.down');
    jQuery(document).bind('keydown.down', function (evt) {
      hotkeyBrowse(1, 'down');
    });

    jQuery(document).bind('keydown.R', function (evt) {
      cornerstone.fitToWindow(element);

      var viewport = cornerstone.getViewport(element);
      if (viewport.invert === true) {
        viewport.invert = false;
      }
      cornerstone.setViewport(element, viewport);
    });

    $(element).on("CornerstoneImageRendered", onViewportUpdated);

    function onNewImage(e, data) {
      var newImageIdIndex = stack.currentImageIdIndex;

      // Update the slider value
      var slider = document.getElementById('slice-range');
      slider.value = newImageIdIndex;

      var div = e.currentTarget;
      var enabledElement = cornerstone.getEnabledElement(div);

    };

    $(element).on("CornerstoneNewImage", onNewImage);

    for (var i = 0; i < imageIDs.length; i++) {
      cornerstone
        .loadAndCacheImage(imageIDs[i]);
    }

    // Ryan Add
    var curImageIDStr = '';
    if (lmViewer.data.series[obj.cnt].modality == "DX" ||
      lmViewer.data.series[obj.cnt].modality == "DR" ||
      lmViewer.data.series[obj.cnt].modality == "CR") {
      var imageIDs = [];
      var idNum = curImageIDStr.length;
      curImageIDStr = curImageIDStr.substr(0, idNum - 3) + ''
      imageIDs[i] == curImageIDStr;
      var _obj = {
        series: lmViewer.data.seriesArray[obj.cnt],
        imagesid: imageIDs
      };
      lmViewer.fn.loadImages(_obj);
      /*            lmViewer.fn.loadImages(lmViewer.data.hosturl, lmViewer.data.serverURL, lmViewer.data.studyUID, lmViewer.data.seriesArray[cnt], imageIDs,
       'dicom');*/
    }

    cornerstone
      .loadAndCacheImage(imageIDs[0])
      .done(
        function (image) {
          //todo tangzhengxiong 2016/9/19
          lmViewer.ui.hideLoading();
          lmViewer.ui.displayDiv();

          // 开启鼠标操作的功能
          if (lmViewer.data.isDesktop === true) {
            // 鼠标按下去滑动时间
            cornerstoneTools.mouseInput.enable(element);
            // 开启鼠标滑轮的操作
            //	cornerstoneTools.mouseWheelInput.enable(element);

            // 自定义鼠标滑轮
            $(element).on('mousewheel DOMMouseScroll', mouseWheel);

          }
          // 开启手机的手势操作功能
          if (lmViewer.data.isMobile === true) {
            cornerstoneTools.touchInput.enable(element);
          }

          cornerstone.displayImage(element, image);
/*          //todo tangzhengxiong scale
          cornerstoneTools.mouseInput.enable(element);*/
          // display this image
          // set the stack as tool state
          cornerstoneTools.addStackStateManager(element, ['stack']);
          cornerstoneTools.addToolState(element, 'stack', stack);

          if (lmViewer.data.isDesktop === true) {
            //		cornerstoneTools.wwwc.activate(element, 1); // ww/wc is the default tool for left mouse button
            cornerstoneTools.pan.activate(element, 2); // pan is the default tool for middle mouse button
            cornerstoneTools.zoom.activate(element, 4); // zoom is the default tool for right mouse button
            cornerstoneTools.probe.enable(element);
            cornerstoneTools.length.enable(element);
            cornerstoneTools.ellipticalRoi.enable(element);
            cornerstoneTools.rectangleRoi.enable(element);
            cornerstoneTools.angle.enable(element);
            cornerstoneTools.highlight.enable(element);
            //todo tangzhengxiong scale
            cornerstoneTools.freehand.enable(element);
            cornerstoneTools.freehand.activate(element, 1);
            // 激活鼠标滑轮的功能
            //		cornerstoneTools.stackScrollWheel.activate(element);
          }

          if (lmViewer.data.isMobile === true) {
            // stack scroll
            cornerstoneTools.stackScrollTouchDrag.activate(element);
          }

          var curGroupIndex = lmViewer.data.groupIndex[obj.cnt];
          lmViewer.data.synchronizers[curGroupIndex].add(element);
          lmViewer.data.multiSeries.push(parseInt(1));

          function disableAllTools() {
            if (lmViewer.data.isDesktop === true) {
              cornerstoneTools.wwwc.disable(element);
              $(element).off('CornerstoneToolsMouseDrag', mouseDragWWWL);
              cornerstoneTools.pan.activate(element, 2); // 2 is middle mouse button
              cornerstoneTools.zoom.activate(element, 4); // 4 is right mouse button
              cornerstoneTools.probe.deactivate(element, 1);
              cornerstoneTools.length.deactivate(element, 1);
              cornerstoneTools.ellipticalRoi.deactivate(element, 1);
              cornerstoneTools.rectangleRoi.deactivate(element, 1);
              cornerstoneTools.simpleAngle.deactivate(element, 1);
              cornerstoneTools.highlight.deactivate(element, 1);
              cornerstoneTools.freehand.deactivate(element, 1);
              cornerstoneTools.wwwcRegion.disable(element);

              $('#imageContainer').removeClass('adjust');
              $('#imageContainer').removeClass('move');
              $('#imageContainer').removeClass('zoom');
            }
            if (lmViewer.data.isMobile === true) {
              cornerstoneTools.panTouchDrag.deactivate(element);
              cornerstoneTools.rotateTouchDrag.deactivate(element);
              cornerstoneTools.rotateTouch.disable(element);
              cornerstoneTools.ellipticalRoiTouch.deactivate(element);
              cornerstoneTools.simpleAngleTouch.deactivate(element);
              cornerstoneTools.rectangleRoiTouch.deactivate(element);
              cornerstoneTools.lengthTouch.deactivate(element);
              cornerstoneTools.probeTouch.deactivate(element);
              cornerstoneTools.zoomTouchDrag.deactivate(element);
              cornerstoneTools.wwwcTouchDrag.deactivate(element);
              cornerstoneTools.stackScrollTouchDrag.deactivate(element);
              $('#image00').off('CornerstoneToolsTouchDrag');
            }
          }


          function clearIconsColor(iconID) {
            $("#enableWindowLevelTool span").css("color", "#505050");
            $("#zoom span").css("color", "#505050");
            $("#enableLength span").css("color", "#505050");
            $("#probe span").css("color", "#505050");
            $("#circleroi span").css("color", "#505050");
            $("#ShowAnnotation span").css("color", "#505050");
            $("#UnShowAnnotation span").css("color", "#505050");
            $("#saveImg span").css("color", "#505050");
            $("#rectangleroi span").css("color", "#505050");
            $("#angle span").css("color", "#505050");
            $("#wwwc span").css("color", "#505050");
            $("#pan span").css("color", "#505050");
            $("#" + iconID + " span").css("color", "#38c500");
          }


          // the mouseWheel event defined by me -------------------------------Updated by TanQilu

          var index = 1;
          function mouseWheel(e) {
            // lmViewer.ui.hideDiv();
            $('#imageContainer').removeClass('adjust');
            $('#enableWindowLevelTool').css('background-color', '#000');
            lmViewer.data.contrastButtonPressed = false;

            disableAllTools();
            lmViewer.ui.recoverButtonColor();
            cornerstoneTools.wwwc.deactivate(element, 1);

            for (var i = 0; i < lmViewer.data.iWindowHNum * lmViewer.data.iWindowVNum; i++) {
              if (i >= lmViewer.data.seriesArray.length) {
                break;
              }
              // find the row and column indexes of this element
              var eleRowIdx = parseInt(i / lmViewer.data.iWindowVNum);
              var eleColumnIdx = parseInt(i - eleRowIdx * lmViewer.data.iWindowVNum);
              var curElement = $('#image' + eleRowIdx.toString() + eleColumnIdx.toString()).get(0);
              if (curElement == undefined) {
                continue;
              }

              $(curElement).off('CornerstoneToolsMouseDrag');
              var _obj = {
                element: curElement,
                image: undefined
              };
              var seriesNum = lmViewer.fn.getImgIndex(_obj).series;

              if (lmViewer.data.groupIndex[i] == lmViewer.data.groupIndex[obj.cnt]) {
                // if(synchrSwitch == false) {
                // 	if(i != cnt) continue;
                // }
                // get the scale of every window which will display the next image
                var enabledElement = cornerstone.getEnabledElement(curElement);

                // delete the last image
                var canvas = enabledElement.canvas;
                var context = canvas.getContext('2d');
                context.clearRect(0, 0, canvas.width, canvas.height);
                context.transform(1, 0, 0, 1, 0, 0);
                /*
                 context.font = 'italic bold 40px Arial';
                 context.textAlign = 'center';
                 context.textBaseline = 'middle';
                 var linearGrad = context.createLinearGradient(canvas.width/4,canvas.height/2,
                 3*canvas.width/4,canvas.height/2);
                 linearGrad.addColorStop(0.0,'red');
                 linearGrad.addColorStop(0.5,'yellow');
                 linearGrad.addColorStop(1.0,'green');
                 context.strokeStyle = linearGrad;
                 context.strokeText('loading...',canvas.width/2,canvas.height/2);
                 */


                context.textAlign = 'left';
                context.textBaseline = 'top';
                context.strokeStyle = '#DF5326';
                context.font = 'bold 24px arial';
                context.fillStyle = 'orange';
                //todo tangzhengxiong 2016/9/19
                //context.fillText("载入中...", canvas.width / 2 - 50, canvas.height / 2 + 12);
                //lmViewer.ui.hideDiv();
                lmViewer.ui.showLoading();
                var imgIndex = lmViewer.fn.getImgIndex(_obj);
                var row = parseInt(lmViewer.data.tagArray[imgIndex.series][imgIndex.instance].rows);
                var rowScale = 1;
                if (cornerstone.getImage(curElement).data != undefined) { // DICOM
                  rowScale = row / 512;
                }
                var viewport = cornerstone.getEnabledElement(curElement).viewport;
                lmViewer.data.imageScale[i] = (viewport.scale * rowScale).toFixed(2);
                lmViewer.data.imageScale[i] = (rowScale).toFixed(2);
                //todo
                // display the next image of the current window and its synchronized windows
                if (e.originalEvent.deltaY > 0) {
                  if (lmViewer.data.wheelInstanceNum[i] + 1 < lmViewer.data.seriesArray[seriesNum].instance.length) {
                    lmViewer.data.wheelInstanceNum[i]++;
                  }
                } else if (e.originalEvent.deltaY < 0) {
                  if (lmViewer.data.wheelInstanceNum[i] - 1 > -1) {
                    lmViewer.data.wheelInstanceNum[i]--;
                  }
                }
                //	 if(getDicomButtonPressed){
                //		selectNewImage(wheelInstanceNum[i]);
                //	 } else {

                lmViewer.data.currentStatus.instance = lmViewer.data.seriesArray[seriesNum].instance[lmViewer.data.wheelInstanceNum[i]];
                lmViewer.fn.RT.setCurrentTag();

                var _readjustInstanceWWWLObj = {
                  index: lmViewer.data.wheelInstanceNum[i],
                  element: curElement
                };
                lmViewer.fn.readjustInstanceWWWL(_readjustInstanceWWWLObj);
                //todo tangzhengxiong 2016/9/19
                if(lmViewer.data.RT.isContour){
                  lmViewer.fn.RT.showImageLines();
                }
                /*
                * 9.26 David 修改为按照position位置找图片
                *
                * */

                // lmViewer.RT.DoseGridFrame.ctrl.AppendToDiv(_readjustInstanceWWWLObj.index,"image00");
                // lmViewer.RT.DoseGridFrame.ctrl.AppendToDivByPosition(299.5,"image00");

                /*
                * 第一张
                * */
                // lmViewer.RT.DoseGridFrame.ctrl.AppendToDivByPosition(-0.5,"image00");
                /*
                * 第二章图片
                * */





                // var position_z = 2.5;
                // var position_z = 482.5 - index * 2.5;
                // // var position_z = lmViewer.data.currentStatus.tag.imagePosition.split("\\")[2];
                // lmViewer.RT.DoseGridFrame.fn.srv.get_doseGridFrame(position_z,function (data) {
                //   lmViewer.RT.DoseGridFrame.ctrl.AppendToDivByPosition(position_z,"image00");
                // });


                //	 }

                var endIdx = curElement.children[2].innerHTML.indexOf('Img：') + 4;
                var startIdx = curElement.children[2].innerHTML.indexOf('/');
                var displatText = curElement.children[2].innerHTML.substring(0, endIdx) +
                  (lmViewer.data.wheelInstanceNum[i] + 1).toString() +
                  curElement.children[2].innerHTML.substring(startIdx);
                curElement.children[2].innerHTML = displatText;
                if (lmViewer.data.referenceLineButtonPressed) {
                  lmViewer.fn.updateAllImageDisplayed();
                  var _drawReferenceLineObj = {
                    element: element
                  };
                  lmViewer.fn.drawReferenceLine(_drawReferenceLineObj);
                }
              }
            }
          }

          // when the ww/wc is being adjusted, this mouseDrag event is
          // used to record the current ww/wc ------ Updated by TanQilu
          function mouseDragWWWL(e, eventData) {
            cornerstone.imageCache.purgeCache();
            for (var eleRowIndex = 0; eleRowIndex < lmViewer.data.iWindowHNum; eleRowIndex++) {
              for (var eleColumnIndex = 0; eleColumnIndex < lmViewer.data.iWindowVNum; eleColumnIndex++) {
                var elementIdx = 0;

                if ('' != lmViewer.data.sort && 1 == lmViewer.data.iWindowVNum && 1 == lmViewer.data.iWindowHNum) {
                  elementIdx = parseInt(lmViewer.data.sort);
                } else {
                  elementIdx = eleRowIndex * lmViewer.data.iWindowVNum + eleColumnIndex;
                }
                if (elementIdx < lmViewer.data.iSeriesNum) {
                  // get the window width from the viewport
                  var startIndexOfWW = $('#mrbottomleft' + elementIdx.toString()).html().indexOf("WW") + 3;
                  var endIndexOfWW = $('#mrbottomleft' + elementIdx.toString()).html().indexOf("&nbsp");
                  var newWW = $('#mrbottomleft' + elementIdx.toString()).html().substring(startIndexOfWW, endIndexOfWW);
                  lmViewer.data.globalWW[elementIdx] = parseInt(newWW, 10);
                  if (lmViewer.data.globalWW[elementIdx] <= 1) {
                    lmViewer.data.globalWW[elementIdx] = 1;
                  }

                  // get the window center from the viewport
                  var startIndexOfWL = $('#mrbottomleft' + elementIdx.toString()).html().indexOf("WL") + 3;
                  var endIndexOfWL = $('#mrbottomleft' + elementIdx.toString()).html().indexOf("<br>Zoom");
                  var newWL = $('#mrbottomleft' + elementIdx.toString()).html().substring(startIndexOfWL, endIndexOfWL);
                  lmViewer.data.globalWL[elementIdx] = parseInt(newWL, 10);
                }
              }
            }
          }

          /*                    $('#enableWindowLevelTool').click(function () {
           lmViewer.ui.enableWindowLevelToolClick(element);
           });*/
          if (lmViewer.data.queryParams.imageType === 'jpg' && lmViewer.data.iWindowVNum * lmViewer.data.iWindowHNum > 1) {
            $('#enableWindowLevelTool').click(function () {
              disableAllTools();
              lmViewer.ui.recoverButtonColor();
              clearIconsColor("enableWindowLevelTool");
              $('#enableWindowLevelTool').css('background-color', 'gray');

              $('#imageContainer').addClass('adjust');
              lmViewer.data.contrastButtonPressed = true;
              if (lmViewer.data.isDesktop) {
                $(element).off('CornerstoneToolsMouseDrag');
              };
  /*            if(lmViewer.data.RT.isContour){d
                lmViewer.fn.RT.showImageLines();
              }*/
            });
          } else {
            $('#enableWindowLevelTool').click(function () {
              // Tool button event handlers that set the new active
              //			$('#modalProgressGlobal').modal('show');
              disableAllTools();
              lmViewer.ui.recoverButtonColor();
              clearIconsColor("enableWindowLevelTool");
              $('#enableWindowLevelTool').css('background-color', 'gray');

              $('#imageContainer').addClass('adjust');
              lmViewer.data.contrastButtonPressed = true;
              var _getDicomObj = {
                element: element
              };
              var newImageId = lmViewer.fn.getDicom(_getDicomObj);

              cornerstone.loadAndCacheImage(newImageId).then(function (image) {
                cornerstone.displayImage(element, image);
                var viewport = cornerstone.getEnabledElement(element).viewport;
                viewport.voi.windowCenter = image.windowCenter;
                viewport.voi.windowWidth = image.windowWidth;

                // element 的行列索引
                var eleRowIndex = element.id.substring(
                  element.id.indexOf('image') + 5,
                  element.id.indexOf('image') + 6);
                var eleColumnIndex = element.id.substring(
                  element.id.indexOf('image') + 6);
                eleRowIndex = parseInt(eleRowIndex);
                eleColumnIndex = parseInt(eleColumnIndex);
                var elementIdx = eleRowIndex * lmViewer.data.iWindowVNum + eleColumnIndex;

                lmViewer.data.globalWL[elementIdx] = image.windowCenter;
                lmViewer.data.globalWW[elementIdx] = image.windowWidth;
                lmViewer.data.initialWL[elementIdx] = lmViewer.data.globalWL[elementIdx];
                lmViewer.data.initialWW[elementIdx] = lmViewer.data.globalWW[elementIdx];

                cornerstone.setViewport(element, viewport);
                lmViewer.fn.triggerResize();
              });

              if (lmViewer.data.isDesktop === true) {
                // record the current window width and center, used on PC
                $(element).off('CornerstoneToolsMouseDrag');
                $(element).on('CornerstoneToolsMouseDrag', mouseDragWWWL);
                cornerstoneTools.wwwc.activate(element, 1);
              }
              if (lmViewer.data.isMobile) {
                // record the current window width and center
                $('#image00').on('CornerstoneToolsTouchDrag', function (e, eventData) {
                  cornerstoneTools.wwwcTouchDrag.activate(element);

                  var elementIdx = parseInt(lmViewer.data.sort);
                  // get the window width from the viewport
                  var startIndexOfWW = $('#mrbottomleft' + lmViewer.data.sort.toString()).html().indexOf("WW") + 3;
                  var endIndexOfWW = $('#mrbottomleft' + lmViewer.data.sort.toString()).html().indexOf("&nbsp");
                  var newWW = $('#mrbottomleft' + lmViewer.data.sort.toString()).html().substring(startIndexOfWW, endIndexOfWW);
                  lmViewer.data.globalWW[elementIdx] = parseInt(newWW, 10);

                  // get the window center from the viewport
                  var startIndexOfWL = $('#mrbottomleft' + lmViewer.data.sort.toString()).html().indexOf("WL") + 3;
                  var endIndexOfWL = $('#mrbottomleft' + lmViewer.data.sort.toString()).html().indexOf("<br>Zoom");
                  var newWL = $('#mrbottomleft' + lmViewer.data.sort.toString()).html().substring(startIndexOfWL, endIndexOfWL);
                  lmViewer.data.globalWL[elementIdx] = parseInt(newWL, 10);
                });
              }
            });
          }


          $('#enableScrollStack').click(function () {
            humane.log("滑动滚动浏览");
            disableAllTools();
            lmViewer.ui.recoverButtonColor();
            $('#enableScrollStack').css('background-color', 'gray');

            if (lmViewer.data.isDesktop === true) {
              cornerstoneTools.stackScrollWheel.activate(element);
            }
            if (lmViewer.data.isMobile === true) {
              // get the scale of every window which will display the next image
              var curElement = $('#image00').get(0);
              var enabledElement = cornerstone.getEnabledElement(curElement);
              var _obj = {
                element: curElement,
                image: undefined
              };
              var imgIndex = lmViewer.fn.getImgIndex(_obj);
              var row = parseInt(lmViewer.data.tagArray[imgIndex.series][imgIndex.instance].rows);
              var rowScale = 1;
              if (cornerstone.getImage(curElement).data != undefined) { // DICOM
                rowScale = row / 512;
              }
              var viewport = cornerstone.getEnabledElement(curElement).viewport;
              lmViewer.data.imageScale[0] = (viewport.scale * rowScale).toFixed(2);

              $('#image00').on('CornerstoneToolsTouchDrag', function (e, eventData) {
                if (eventData.deltaPoints.image.y > 0) {
                  if (lmViewer.data.curImageNum + 1 < lmViewer.data.seriesArray[sort].instance.length) {
                    lmViewer.data.curImageNum++;
                  }
                  //              if(contrastButtonPressed && navigator.userAgent.indexOf( 'iPhone') == -1){
                  var _readjustInstanceWWWLObj = {
                    index: lmViewer.data.curImageNum,
                    element: curElement
                  };
                  lmViewer.fn.readjustInstanceWWWL(_readjustInstanceWWWLObj);
                  //             } else {
                  //                   selectNewImage(curImageNum);
                  //             }

                } else if (eventData.deltaPoints.image.y < 0) {
                  if (lmViewer.data.curImageNum - 1 > -1) {
                    lmViewer.data.curImageNum--;
                  }
                  //              if(contrastButtonPressed && navigator.userAgent.indexOf( 'iPhone') == -1){
                  var _readjustInstanceWWWLObj = {
                    index: lmViewer.data.curImageNum,
                    element: curElement
                  };
                  lmViewer.fn.readjustInstanceWWWL(_readjustInstanceWWWLObj);
                  //             } else {
                  //                   selectNewImage(curImageNum);
                  //             }
                }
              });
              //          cornerstoneTools.stackScrollTouchDrag.activate(element);
            }
          });

          $('#pan').click(function () {
            disableAllTools();
            lmViewer.ui.recoverButtonColor();
            $('#pan').css('background-color', 'gray');
            clearIconsColor("pan");
            $('#imageContainer').addClass('move');

            if (lmViewer.data.isDesktop === true) {
              cornerstoneTools.pan.activate(element,  3);
              //todo tangzhengxiong 2016/9/26
              if(lmViewer.data.RT.isContour){
                lmViewer.fn.RT.showImageLines();
              }
            }
            if (lmViewer.data.isMobile === true) {
              cornerstoneTools.panTouchDrag.activate(element);
            }

          });

          $('#zoom').click(function () {

            disableAllTools();
            lmViewer.ui.recoverButtonColor();
            clearIconsColor("zoom");
            $('#zoom').css('background-color', 'gray');

            $('#imageContainer').addClass('zoom');
            if (lmViewer.data.isDesktop === true) {
              cornerstoneTools.zoom.activate(element,
                5);
              // 5 means left mouse button and right
              // mouse button
            }
            if (lmViewer.data.isMobile === true) {
              cornerstoneTools.zoomTouchDrag.activate(element);
            }
          });

          $('#RotateLeft').click(function () {
            disableAllTools();
            lmViewer.ui.recoverButtonColor();
            $('#RotateLeft').css('background-color', 'gray');

            var enabledElement = cornerstone
              .getEnabledElement(element);
            enabledElement.viewport.rotation = enabledElement.viewport.rotation - 90;
            cornerstone.updateImage(element);
          });
          $('#RotateRight').click(function () {
            disableAllTools();
            lmViewer.ui.recoverButtonColor();
            $('#RotateRight').css('background-color', 'gray');

            var enabledElement = cornerstone
              .getEnabledElement(element);
            enabledElement.viewport.rotation = enabledElement.viewport.rotation + 90;
            cornerstone.updateImage(element);
          });

          $('#hFlip').click(function (e) {
            lmViewer.ui.recoverButtonColor();
            $('#hFlip').css('background-color', 'gray');

            var viewport = cornerstone.getViewport(element);
            viewport.hflip = !viewport.hflip;
            cornerstone.setViewport(element, viewport);
          });

          $('#vFlip').click(function (e) {
            lmViewer.ui.recoverButtonColor();
            $('#vFlip').css('background-color', 'gray');

            var viewport = cornerstone.getViewport(element);
            viewport.vflip = !viewport.vflip;
            cornerstone.setViewport(element, viewport);
          });

          $('#reset').click(function () {
            disableAllTools();
            lmViewer.ui.recoverButtonColor();
            $('#reset').css('background-color', 'gray');

            cornerstone.fitToWindow(element);
            var viewport = cornerstone.getViewport(element);
            if (viewport.invert === true) {
              viewport.invert = false;
            }
            viewport.vflip = false;
            viewport.hflip = false;
            cornerstone.setViewport(element, viewport);

            cornerstoneTools.clearToolState(element, "length");
            cornerstoneTools.clearToolState(element, "probe");
            cornerstoneTools.clearToolState(element, "ellipticalRoi");
            cornerstoneTools.clearToolState(element, "rectangleRoi");
            cornerstoneTools.clearToolState(element, "simpleAngle");
            cornerstoneTools.clearToolState(element, "wwwcRegion");//局部对比度
            //复原图像翻转
            var enabledElement = cornerstone.getEnabledElement(element);
            enabledElement.viewport.rotation = 0;
            cornerstoneTools.clearToolState(element, "wwwc");
            cornerstone.updateImage(element);
          });


          $('#enableLength').click(function () {
            disableAllTools();
            lmViewer.ui.recoverButtonColor();
            clearIconsColor("enableLength");
            $('#enableLength').css('background-color', 'gray');

            // get the scale of every window which will display the next image
            var enabledElement = cornerstone.getEnabledElement(element);
            var _obj = {
              element: element,
              image: undefined
            };
            var imgIndex = lmViewer.fn.getImgIndex(_obj);
            var row = parseInt(lmViewer.data.tagArray[imgIndex.series][imgIndex.instance].rows);
            var rowScale = 1;
            if (cornerstone.getImage(element).data == undefined) { // JPG
              rowScale = 512 / row;
            }
            var _getDicomObj = {
              element: element
            };
            var newImageId = lmViewer.fn.getDicom(_getDicomObj);
            cornerstone.loadAndCacheImage(newImageId).then(function (image) {
              cornerstone.displayImage(element, image);
              var viewport = cornerstone.getEnabledElement(element).viewport;

              // element 的行列索引
              var eleRowIndex = element.id.substring(
                element.id.indexOf('image') + 5,
                element.id.indexOf('image') + 6);
              var eleColumnIndex = element.id.substring(
                element.id.indexOf('image') + 6);
              eleRowIndex = parseInt(eleRowIndex);
              eleColumnIndex = parseInt(eleColumnIndex);
              var elementIdx = 0;
              if (lmViewer.data.iWindowVNum * lmViewer.data.iWindowHNum == 1) {
                elementIdx = lmViewer.data.sort;
              } else {
                elementIdx = eleRowIndex * lmViewer.data.iWindowVNum + eleColumnIndex;
              }

              lmViewer.data.initialWL[elementIdx] = image.windowCenter;
              lmViewer.data.initialWW[elementIdx] = image.windowWidth;
              if (lmViewer.data.globalWW[elementIdx] != undefined && lmViewer.data.globalWL[elementIdx] != undefined) {
                viewport.voi.windowCenter = lmViewer.data.globalWL[elementIdx];
                viewport.voi.windowWidth = lmViewer.data.globalWW[elementIdx];
              } else {
                viewport.voi.windowCenter = lmViewer.data.initialWL[elementIdx];
                viewport.voi.windowWidth = lmViewer.data.initialWW[elementIdx];
              }

              lmViewer.data.imageScale[obj.cnt] = parseFloat((viewport.scale * rowScale).toFixed(2));
              viewport.scale = lmViewer.data.imageScale[obj.cnt];

              cornerstone.setViewport(element, viewport);
            });

            if (lmViewer.data.isDesktop === true) {
              cornerstoneTools.length.activate(element, 1);
            }
            if (lmViewer.data.isMobile === true) {
              cornerstoneTools.lengthTouch.activate(element);
            }

          });

          $('#probe').click(function () {
            //		$('#modalProgressGlobal').modal('show');
            disableAllTools();
            lmViewer.ui.recoverButtonColor();
            clearIconsColor("probe");
            $('#probe').css('background-color', 'gray');

            // get the scale of every window which will display the next image
            var enabledElement = cornerstone.getEnabledElement(element);
            var _obj = {
              element: element,
              image: undefined
            };
            var imgIndex = lmViewer.fn.getImgIndex(_obj);
            var row = parseInt(lmViewer.data.tagArray[imgIndex.series][imgIndex.instance].rows);
            var rowScale = 1;
            if (cornerstone.getImage(element).data == undefined) { // JPG
              rowScale = 512 / row;
            }

            var _getDicomObj = {
              element: element
            };
            var newImageId = lmViewer.fn.getDicom(_getDicomObj);
            cornerstone.loadAndCacheImage(newImageId).then(function (image) {
              cornerstone.displayImage(element, image);
              var viewport = cornerstone.getEnabledElement(element).viewport;

              // element 的行列索引
              var eleRowIndex = element.id.substring(
                element.id.indexOf('image') + 5,
                element.id.indexOf('image') + 6);
              var eleColumnIndex = element.id.substring(
                element.id.indexOf('image') + 6);
              eleRowIndex = parseInt(eleRowIndex);
              eleColumnIndex = parseInt(eleColumnIndex);
              var elementIdx = 0;
              if (lmViewer.data.iWindowVNum * lmViewer.data.iWindowHNum == 1) {
                elementIdx = lmViewer.data.sort;
              } else {
                elementIdx = eleRowIndex * lmViewer.data.iWindowVNum + eleColumnIndex;
              }

              lmViewer.data.initialWL[elementIdx] = image.windowCenter;
              lmViewer.data.initialWW[elementIdx] = image.windowWidth;
              if (lmViewer.data.globalWW[elementIdx] != undefined && lmViewer.data.globalWL[elementIdx] != undefined) {
                viewport.voi.windowCenter = lmViewer.data.globalWL[elementIdx];
                viewport.voi.windowWidth = lmViewer.data.globalWW[elementIdx];
              } else {
                viewport.voi.windowCenter = lmViewer.data.initialWL[elementIdx];
                viewport.voi.windowWidth = lmViewer.data.initialWW[elementIdx];
              }

              lmViewer.data.imageScale[obj.cnt] = parseFloat((viewport.scale * rowScale).toFixed(2));
              viewport.scale = lmViewer.data.imageScale[obj.cnt];

              cornerstone.setViewport(element, viewport);
            });
            if (lmViewer.data.isDesktop === true) {
              cornerstoneTools.probe.activate(element, 1);
            }
            if (lmViewer.data.isMobile === true) {
              cornerstoneTools.probeTouch.activate(element);
            }
          });

          $('#circleroi').click(function () {
            disableAllTools();
            lmViewer.ui.recoverButtonColor();
            $('#circleroi').css('background-color', 'gray');
            clearIconsColor("circleroi");

            // get the scale of every window which will display the next image
            var enabledElement = cornerstone.getEnabledElement(element);
            var _obj = {
              element: element,
              image: undefined
            };
            var imgIndex = lmViewer.fn.getImgIndex(_obj);
            var row = parseInt(lmViewer.data.tagArray[imgIndex.series][imgIndex.instance].rows);
            var rowScale = 1;
            if (cornerstone.getImage(element).data == undefined) { // JPG
              rowScale = 512 / row;
            }
            var _getDicomObj = {
              element: element
            };
            var newImageId = lmViewer.fn.getDicom(_getDicomObj);
            cornerstone.loadAndCacheImage(newImageId).then(function (image) {
              cornerstone.displayImage(element, image);
              var viewport = cornerstone.getEnabledElement(element).viewport;

              // element 的行列索引
              var eleRowIndex = element.id.substring(
                element.id.indexOf('image') + 5,
                element.id.indexOf('image') + 6);
              var eleColumnIndex = element.id.substring(
                element.id.indexOf('image') + 6);
              eleRowIndex = parseInt(eleRowIndex);
              eleColumnIndex = parseInt(eleColumnIndex);
              var elementIdx = 0;
              if (lmViewer.data.iWindowVNum * lmViewer.data.iWindowHNum == 1) {
                elementIdx = lmViewer.data.sort;
              } else {
                elementIdx = eleRowIndex * lmViewer.data.iWindowVNum + eleColumnIndex;
              }

              lmViewer.data.initialWL[elementIdx] = image.windowCenter;
              lmViewer.data.initialWW[elementIdx] = image.windowWidth;
              if (lmViewer.data.globalWW[elementIdx] != undefined && lmViewer.data.globalWL[elementIdx] != undefined) {
                viewport.voi.windowCenter = lmViewer.data.globalWL[elementIdx];
                viewport.voi.windowWidth = lmViewer.data.globalWW[elementIdx];
              } else {
                viewport.voi.windowCenter = lmViewer.data.initialWL[elementIdx];
                viewport.voi.windowWidth = lmViewer.data.initialWW[elementIdx];
              }

              lmViewer.data.imageScale[obj.cnt] = parseFloat((viewport.scale * rowScale).toFixed(2));
              viewport.scale = lmViewer.data.imageScale[obj.cnt];

              cornerstone.setViewport(element, viewport);
            });

            if (lmViewer.data.isDesktop === true) {
              cornerstoneTools.ellipticalRoi.activate(element, 1);
            }
            if (lmViewer.data.isMobile === true) {
              cornerstoneTools.ellipticalRoiTouch.activate(element);
            }

          });

          $('#rectangleroi').click(function () {
            disableAllTools();
            lmViewer.ui.recoverButtonColor();
            $('#rectangleroi').css('background-color', 'gray');

            // get the scale of every window which will display the next image
            var enabledElement = cornerstone.getEnabledElement(element);
            var _obj = {
              element: element,
              image: undefined
            };
            var imgIndex = lmViewer.fn.getImgIndex(_obj);
            var row = parseInt(lmViewer.data.tagArray[imgIndex.series][imgIndex.instance].rows);
            var rowScale = 1;
            if (cornerstone.getImage(element).data == undefined) { // JPG
              rowScale = 512 / row;
            }

            var _getDicomObj = {
              element: element
            };
            var newImageId = lmViewer.fn.getDicom(_getDicomObj);
            cornerstone.loadAndCacheImage(newImageId).then(function (image) {
              cornerstone.displayImage(element, image);
              var viewport = cornerstone.getEnabledElement(element).viewport;

              // element 的行列索引
              var eleRowIndex = element.id.substring(
                element.id.indexOf('image') + 5,
                element.id.indexOf('image') + 6);
              var eleColumnIndex = element.id.substring(
                element.id.indexOf('image') + 6);
              eleRowIndex = parseInt(eleRowIndex);
              eleColumnIndex = parseInt(eleColumnIndex);
              var elementIdx = 0;
              if (lmViewer.data.iWindowVNum * lmViewer.data.iWindowHNum == 1) {
                elementIdx = lmViewer.data.sort;
              } else {
                elementIdx = eleRowIndex * lmViewer.data.iWindowVNum + eleColumnIndex;
              }

              lmViewer.data.initialWL[elementIdx] = image.windowCenter;
              lmViewer.data.initialWW[elementIdx] = image.windowWidth;
              if (lmViewer.data.globalWW[elementIdx] != undefined && lmViewer.data.globalWL[elementIdx] != undefined) {
                viewport.voi.windowCenter = lmViewer.data.globalWL[elementIdx];
                viewport.voi.windowWidth = lmViewer.data.globalWW[elementIdx];
              } else {
                viewport.voi.windowCenter = lmViewer.data.initialWL[elementIdx];
                viewport.voi.windowWidth = lmViewer.data.initialWW[elementIdx];
              }

              lmViewer.data.imageScale[obj.cnt] = parseFloat((viewport.scale * rowScale).toFixed(2));
              viewport.scale = lmViewer.data.imageScale[obj.cnt];

              cornerstone.setViewport(element, viewport);
            });

            if (lmViewer.data.isDesktop === true) {
              cornerstoneTools.rectangleRoi.activate(element, 1);
            }
            if (lmViewer.data.isMobile === true) {
              cornerstoneTools.rectangleRoiTouch.activate(element);
            }
          });

          $('#angle').click(function () {
            disableAllTools();
            lmViewer.ui.recoverButtonColor();
            $('#angle').css('background-color', 'gray');
            clearIconsColor("angle");

            if (lmViewer.data.isDesktop === true) {
              cornerstoneTools.simpleAngle.activate(element, 1);
            }
            if (lmViewer.data.isMobile === true) {
              cornerstoneTools.simpleAngleTouch.activate(element);
            }
          });

          $('#UnShowAnnotation').click(function (e) {
            disableAllTools();
            lmViewer.ui.recoverButtonColor();
            $('#UnShowAnnotation').css('background-color', 'gray');

            cornerstoneTools.probe.disable(element);
            cornerstoneTools.rectangleRoi.disable(element);
            cornerstoneTools.ellipticalRoi.disable(element);
            cornerstoneTools.simpleAngle.disable(element);
            cornerstoneTools.lengthTouch.disable(element);
          });

          $('#ShowAnnotation').click(function (e) {
            disableAllTools();
            lmViewer.ui.recoverButtonColor();
            $('#ShowAnnotation').css('background-color', 'gray');

            cornerstoneTools.probe.enable(element);
            cornerstoneTools.rectangleRoi.enable(element);
            cornerstoneTools.ellipticalRoi.enable(element);
            cornerstoneTools.simpleAngle.enable(element);
            cornerstoneTools.lengthTouch.enable(element);
          });

          $('#wwwc').click(function (e) {
            disableAllTools();
            lmViewer.ui.recoverButtonColor();
            $('#wwwc').css('background-color', 'gray');
            clearIconsColor("wwwc");

            if (lmViewer.data.isDesktop === true) {
              cornerstoneTools.wwwcRegion.activate(element, 1);
            }
          });

          $('#invert').click(function (e) {
            lmViewer.ui.recoverButtonColor();
            $('#invert').css('background-color', 'gray');

            var viewport = cornerstone.getViewport(element);
            if (viewport.invert === true) {
              viewport.invert = false;
            } else {
              viewport.invert = true;
            }
            cornerstone.setViewport(element, viewport);
          });

          $('#WindowLevelHead').click(function (e) {
            disableAllTools();
            lmViewer.ui.recoverButtonColor();
            $('#WindowLevelHead').css('background-color', 'gray');
            $('#imageContainer').addClass('adjust');

            lmViewer.data.contrastButtonPressed = true;
            var _getDicomObj = {
              element: element
            };
            var newImageId = lmViewer.fn.getDicom(_getDicomObj);

            cornerstone.loadAndCacheImage(newImageId).then(function (image) {
              cornerstone.displayImage(element, image);
              var viewport = cornerstone.getEnabledElement(element).viewport;
              var _obj = {
                element: element,
                image: undefined
              };
              var seriesNum = lmViewer.fn.getImgIndex(_obj).series;
              lmViewer.data.initialWL[seriesNum] = image.windowCenter;
              lmViewer.data.initialWW[seriesNum] = image.windowWidth;

              viewport.voi.windowCenter = 35;
              viewport.voi.windowWidth = 80;

              // element 的行列索引
              var eleRowIndex = element.id.substring(
                element.id.indexOf('image') + 5,
                element.id.indexOf('image') + 6);
              var eleColumnIndex = element.id.substring(
                element.id.indexOf('image') + 6);
              eleRowIndex = parseInt(eleRowIndex);
              eleColumnIndex = parseInt(eleColumnIndex);

              var elementIdx = 0;
              if ('' != lmViewer.data.sort && 1 == lmViewer.data.iWindowVNum && 1 == lmViewer.data.iWindowHNum) {
                elementIdx = parseInt(lmViewer.data.sort);
              } else {
                elementIdx = eleRowIndex * lmViewer.data.iWindowVNum + eleColumnIndex;
              }

              lmViewer.data.globalWL[elementIdx] = 35;
              lmViewer.data.globalWW[elementIdx] = 80;

              cornerstone.setViewport(element, viewport);
              lmViewer.fn.triggerResize();
              $('#modalProgressGlobal').modal('hide');
            });

            cornerstoneTools.wwwc.activate(element, 1);
            $(element).off('CornerstoneToolsMouseDrag');
            $(element).on('CornerstoneToolsMouseDrag', mouseDragWWWL);

            // record the current window width and center, used on PC

            //							var viewport = cornerstone.getViewport(element);
            //							viewport.voi.windowWidth = 80;
            //							viewport.voi.windowCenter = 35;
            //							cornerstone.setViewport(element, viewport);
          });

          $('#WindowLevelLung').click(function (e) {
            disableAllTools();
            lmViewer.ui.recoverButtonColor();
            $('#WindowLevelLung').css('background-color', 'gray');
            //		$('#modalProgressGlobal').modal('show');
            $('#imageContainer').addClass('adjust');

            lmViewer.data.contrastButtonPressed = true;
            var _getDicomObj = {
              element: element
            };
            var newImageId = lmViewer.fn.getDicom(_getDicomObj);

            cornerstone.loadAndCacheImage(newImageId).then(function (image) {
              cornerstone.displayImage(element, image);
              var viewport = cornerstone.getEnabledElement(element).viewport;
              var _obj = {
                element: element,
                image: undefined
              };
              var seriesNum = lmViewer.fn.getImgIndex(_obj).series;
              lmViewer.data.initialWL[seriesNum] = image.windowCenter;
              lmViewer.data.initialWW[seriesNum] = image.windowWidth;

              viewport.voi.windowCenter = -500;
              viewport.voi.windowWidth = 1500;

              // element 的行列索引
              var eleRowIndex = element.id.substring(
                element.id.indexOf('image') + 5,
                element.id.indexOf('image') + 6);
              var eleColumnIndex = element.id.substring(
                element.id.indexOf('image') + 6);
              eleRowIndex = parseInt(eleRowIndex);
              eleColumnIndex = parseInt(eleColumnIndex);

              var elementIdx = 0;
              if ('' != lmViewer.data.sort && 1 == lmViewer.data.iWindowVNum && 1 == lmViewer.data.iWindowHNum) {
                elementIdx = parseInt(lmViewer.data.sort);
              } else {
                elementIdx = eleRowIndex * lmViewer.data.iWindowVNum + eleColumnIndex;
              }

              lmViewer.data.globalWL[elementIdx] = -500;
              lmViewer.data.globalWW[elementIdx] = 1500;

              cornerstone.setViewport(element, viewport);
              lmViewer.fn.triggerResize();
              $('#modalProgressGlobal').modal('hide');
            });

            cornerstoneTools.wwwc.activate(element, 1);
            $(element).off('CornerstoneToolsMouseDrag');
            $(element).on('CornerstoneToolsMouseDrag', mouseDragWWWL);

            //							var viewport = cornerstone.getViewport(element);
            //							viewport.voi.windowWidth = 800;
            //							viewport.voi.windowCenter = -700;
            //							cornerstone.setViewport(element, viewport);
          });

          $('#WindowLevelChest').click(function (e) {
            disableAllTools();
            lmViewer.ui.recoverButtonColor();
            $('#WindowLevelChest').css('background-color', 'gray');
            //			$('#modalProgressGlobal').modal('show');
            $('#imageContainer').addClass('adjust');

            lmViewer.data.contrastButtonPressed = true;
            var _getDicomObj = {
              element: element
            };
            var newImageId = lmViewer.fn.getDicom(_getDicomObj);

            cornerstone.loadAndCacheImage(newImageId).then(function (image) {
              cornerstone.displayImage(element, image);
              var viewport = cornerstone.getEnabledElement(element).viewport;
              var _obj = {
                element: element,
                image: undefined
              };
              var seriesNum = lmViewer.fn.getImgIndex(_obj).series;
              lmViewer.data.initialWL[seriesNum] = image.windowCenter;
              lmViewer.data.initialWW[seriesNum] = image.windowWidth;

              viewport.voi.windowCenter = 50;
              viewport.voi.windowWidth = 500;

              // element 的行列索引
              var eleRowIndex = element.id.substring(
                element.id.indexOf('image') + 5,
                element.id.indexOf('image') + 6);
              var eleColumnIndex = element.id.substring(
                element.id.indexOf('image') + 6);
              eleRowIndex = parseInt(eleRowIndex);
              eleColumnIndex = parseInt(eleColumnIndex);

              var elementIdx = 0;
              if ('' != lmViewer.data.sort && 1 == lmViewer.data.iWindowVNum && 1 == lmViewer.data.iWindowHNum) {
                elementIdx = parseInt(lmViewer.data.sort);
              } else {
                elementIdx = eleRowIndex * lmViewer.data.iWindowVNum + eleColumnIndex;
              }

              lmViewer.data.globalWL[elementIdx] = 50;
              lmViewer.data.globalWW[elementIdx] = 500;

              cornerstone.setViewport(element, viewport);
              lmViewer.fn.triggerResize();
              $('#modalProgressGlobal').modal('hide');
            });

            cornerstoneTools.wwwc.activate(element, 1);
            $(element).off('CornerstoneToolsMouseDrag');
            $(element).on('CornerstoneToolsMouseDrag', mouseDragWWWL);

            //							var viewport = cornerstone.getViewport(element);
            //							viewport.voi.windowWidth = 500;
            //							viewport.voi.windowCenter = 50;
            //							cornerstone.setViewport(element, viewport);
          });

          $('#WindowLevelAbdomen').click(function (e) {
            disableAllTools();
            lmViewer.ui.recoverButtonColor();
            $('#WindowLevelAbdomen').css('background-color', 'gray');
            //				$('#modalProgressGlobal').modal('show');
            $('#imageContainer').addClass('adjust');

            lmViewer.data.contrastButtonPressed = true;
            var _getDicomObj = {
              element: element
            };
            var newImageId = lmViewer.fn.getDicom(_getDicomObj);

            cornerstone.loadAndCacheImage(newImageId).then(function (image) {
              cornerstone.displayImage(element, image);
              var viewport = cornerstone.getEnabledElement(element).viewport;
              var _obj = {
                element: element,
                image: undefined
              };
              var seriesNum = lmViewer.fn.getImgIndex(_obj).series;
              lmViewer.data.initialWL[seriesNum] = image.windowCenter;
              lmViewer.data.initialWW[seriesNum] = image.windowWidth;

              viewport.voi.windowCenter = 50;
              viewport.voi.windowWidth = 350;

              // element 的行列索引
              var eleRowIndex = element.id.substring(
                element.id.indexOf('image') + 5,
                element.id.indexOf('image') + 6);
              var eleColumnIndex = element.id.substring(
                element.id.indexOf('image') + 6);
              eleRowIndex = parseInt(eleRowIndex);
              eleColumnIndex = parseInt(eleColumnIndex);

              var elementIdx = 0;
              if ('' != lmViewer.data.sort && 1 == lmViewer.data.iWindowVNum && 1 == lmViewer.data.iWindowHNum) {
                elementIdx = parseInt(lmViewer.data.sort);
              } else {
                elementIdx = eleRowIndex * lmViewer.data.iWindowVNum + eleColumnIndex;
              }

              lmViewer.data.globalWL[elementIdx] = 50;
              lmViewer.data.globalWW[elementIdx] = 350;

              cornerstone.setViewport(element, viewport);
              lmViewer.fn.triggerResize();
              $('#modalProgressGlobal').modal('hide');
            });

            cornerstoneTools.wwwc.activate(element, 1);
            $(element).off('CornerstoneToolsMouseDrag');
            $(element).on('CornerstoneToolsMouseDrag', mouseDragWWWL);

            //							var viewport = cornerstone.getViewport(element);
            //							viewport.voi.windowWidth = 170;
            //							viewport.voi.windowCenter = 35;
            //							cornerstone.setViewport(element, viewport);
          });

          $('#WindowLevelBone').click(function (e) {
            disableAllTools();
            lmViewer.ui.recoverButtonColor();
            $('#WindowLevelBone').css('background-color', 'gray');
            //			$('#modalProgressGlobal').modal('show');
            $('#imageContainer').addClass('adjust');

            lmViewer.data.contrastButtonPressed = true;
            var _getDicomObj = {
              element: element
            };
            var newImageId = lmViewer.fn.getDicom(_getDicomObj);

            cornerstone.loadAndCacheImage(newImageId).then(function (image) {
              cornerstone.displayImage(element, image);
              var viewport = cornerstone.getEnabledElement(element).viewport;
              var _obj = {
                element: element,
                image: undefined
              };
              var seriesNum = lmViewer.fn.getImgIndex(_obj).series;
              lmViewer.data.initialWL[seriesNum] = image.windowCenter;
              lmViewer.data.initialWW[seriesNum] = image.windowWidth;
              ;

              viewport.voi.windowCenter = 300;
              viewport.voi.windowWidth = 1500;

              // element 的行列索引
              var eleRowIndex = element.id.substring(
                element.id.indexOf('image') + 5,
                element.id.indexOf('image') + 6);
              var eleColumnIndex = element.id.substring(
                element.id.indexOf('image') + 6);
              eleRowIndex = parseInt(eleRowIndex);
              eleColumnIndex = parseInt(eleColumnIndex);

              var elementIdx = 0;
              if ('' != lmViewer.data.sort && 1 == lmViewer.data.iWindowVNum && 1 == lmViewer.data.iWindowHNum) {
                elementIdx = parseInt(lmViewer.data.sort);
              } else {
                elementIdx = eleRowIndex * lmViewer.data.iWindowVNum + eleColumnIndex;
              }

              lmViewer.data.globalWL[elementIdx] = 300;
              lmViewer.data.globalWW[elementIdx] = 1500;

              cornerstone.setViewport(element, viewport);
              lmViewer.fn.triggerResize();
              $('#modalProgressGlobal').modal('hide');
            });

            cornerstoneTools.wwwc.activate(element, 1);
            $(element).off('CornerstoneToolsMouseDrag');
            $(element).on('CornerstoneToolsMouseDrag', mouseDragWWWL);

            //							var viewport = cornerstone.getViewport(element);
            //							viewport.voi.windowWidth = 1500;
            //							viewport.voi.windowCenter = 300;
            //							cornerstone.setViewport(element, viewport);
          });

          lmViewer.fn.triggerResize();
          // $('#modalProgressGlobal').modal('hide');
          if (lmViewer.data.isDesktop) {
            var _plottingScaleObj = {
              element: element
            };
            lmViewer.fn.plottingScale(_plottingScaleObj);
          }
        });
  };
  ui.showSeries = function () {
    //colIndex, rowIndex
    //lmViewer.data.iWindowVNum, lmViewer.data.iWindowHNum
    // 显示序列

    var _colIndex = lmViewer.data.iWindowVNum;
    var _rowIndex = lmViewer.data.iWindowHNum;
    $('#toolbar-function-simple').css('display', 'none');
    $('#toolbar-function').css('display', 'block');
    $('#mrtopleft').css('display', 'block');
    lmViewer.data.clickedSeries = -1;
    for (var i = 0; i < lmViewer.data.iSeriesNum; i++) {
      if (lmViewer.data.loadedIndex[i] != -1) {
        lmViewer.data.loadedIndex[i] = -1;
      }
    }

    lmViewer.data.autoPlayButtonPressed = true;

    $('#imageContainer').removeClass('adjust');
    $('#imageContainer').removeClass('move');
    $('#imageContainer').removeClass('zoom');
    //getDicomButtonPressed = false;

    lmViewer.data.initialWW = [];
    lmViewer.data.initialWL = [];
    lmViewer.data.globalWW = [];
    lmViewer.data.globalWL = [];
    lmViewer.data.imageScale = [];
    lmViewer.data.multiSeries = [];

    if (lmViewer.data.seriesArray.length < _colIndex) {
      _colIndex = lmViewer.data.seriesArray.length;
    }

    if (_colIndex * _rowIndex > lmViewer.data.seriesArray.length) {
      _rowIndex = Math.ceil(lmViewer.data.seriesArray.length / _colIndex);
    }

    lmViewer.data.iWindowVNum = _colIndex;
    lmViewer.data.iWindowHNum = _rowIndex;
    lmViewer.data.viewportNum = lmViewer.data.iWindowHNum * lmViewer.data.iWindowVNum - 1;

    var divContent = '';

    var cnt = parseInt('0');

    for (var x = 0; x < lmViewer.data.iWindowHNum; x++) {
      for (var y = 0; y < lmViewer.data.iWindowVNum; y++) {
        // For each series, load it
        if (cnt < lmViewer.data.totalSeries) {
          var imageDivId = "image" + x.toString() + y.toString();
          // 解除上次绑定
          var element = $('#' + imageDivId).get(0);
          $(element).off("CornerstoneImageRendered");
          cnt++;
        }
      }
    }

    cnt = 0;

    if ('' != lmViewer.data.sort && 1 == lmViewer.data.iWindowVNum && 1 == lmViewer.data.iWindowHNum) {
      cnt = parseInt(lmViewer.data.sort);
    }
    // TODO
    divContent += '<table id="tableViews" style="width:100%;border:1px solid #D5D5D5;background-color: #000;">';

    for (var x = 0; x < _rowIndex; x++) {
      divContent += '<tr height="' + 100 / (_rowIndex) + '%">';
      for (var y = 0; y < _colIndex; y++) {

        // For each series, load it
        if (cnt < lmViewer.data.totalSeries) {
          var imageDivId = "image" + x.toString() + y.toString();
          divContent += '<td style="padding:0;margin:0;border:1px solid #454444;" width="'
            + 100 / _colIndex + '%" >';
          divContent += '<div style="width:'
            + 100
            + '%;'
            + 'height:'
            + 100
            + '%'
            + ';position:relative;display:inline-block;color:white;"'
            + 'oncontextmenu="return false" class="cornerstone-enabled-image" unselectable="on" onselectstart="return false;"'
            + 'onmousedown="return false;">';
          divContent += '<div id="' + imageDivId
            + '" onclick="lmViewer.ui.showCurrentSeries('
            + imageDivId.toString() + ',' + cnt + ')"></div>';
          divContent += '</div>' + '</td>';

          cnt++;

        }
      }
      divContent += '</tr>';
    }
    divContent += '</table>';
    document.getElementById("imageContainer").innerHTML = divContent;
    var cnt = parseInt('0');
    if ('' != lmViewer.data.sort && 1 == lmViewer.data.iWindowVNum && 1 == lmViewer.data.iWindowHNum) {
      cnt = parseInt(lmViewer.data.sort);
    }
    for (var x = 0; x < _rowIndex; x++) {
      for (var y = 0; y < _colIndex; y++) {
        // For each series, load it
        if (cnt < lmViewer.data.totalSeries) {
          var imageDivId = "image" + x.toString() + y.toString();
          // 设置图片显示位置区域
          var _showEachSeriesObj = {
            imageDivId: imageDivId,
            cnt: cnt
          };
          lmViewer.ui.showEachSeries(_showEachSeriesObj);
          cnt++;
        }
      }
    }

  };
  ui.resizeCanvas_share = function () {
    $('#liViewer').css('marginLeft', ((document.body.clientWidth - $('#toolbar-function').width()) / 2).toString() + 'px');//设置工具栏的位置
    var imageTop = ($('#toolbar-function').height()).toString() + 'px';
    $('#content').css('marginTop', imageTop);
    $('#slice-range').css('display', 'none');
    var clientWidth = document.body.clientWidth;
    var clientHeight = document.body.clientHeight;
    if (clientWidth > clientHeight) {
      $('#vertical').css('display', 'block');
      $('#transverse').css('display', 'none');
      $(' #contentDiv').parent().css('position', 'absolute');

      var width = (document.body.clientWidth - $('#vertical').width() - 10).toString() + 'px';
      $(' #contentDiv').parent().css('width', width.toString());
    } else {
      $('#vertical').css('display', 'none');
      $('#transverse').css('display', 'block');
      $('#contentDiv').parent().css('position', "");
    }

    var cnt = parseInt('0');
    var test = 0;

    if (clientWidth > clientHeight) {
      document.getElementById("imageContainer").style.width =
        (document.body.clientWidth - $('#vertical').width()).toString() + 'px';
    } else {
      document.getElementById("imageContainer").style.width =
        document.body.clientWidth.toString() + 'px';
    }

    for (var x = 0; x < lmViewer.data.iWindowHNum; x++) {
      for (var y = 0; y < lmViewer.data.iWindowVNum; y++) {

        var imageDivId = "image" + x.toString() + y.toString();
        var element = $('#' + imageDivId).get(0);

        if (element === undefined) {
          continue;
        }

        var enabledElement = cornerstone.getEnabledElement(element);
        var currCanvas = enabledElement.canvas.getContext('2d').canvas;

        var totalWidth = $('#imageContainer').width() - 1 - lmViewer.data.iWindowVNum - 2 * lmViewer.data.iWindowVNum;
        var totalHeight = document.body.clientHeight - $('#app-nav').height() - $('#tabs1').height() - 6 - 5 * lmViewer.data.iWindowHNum - 2 * lmViewer.data.iWindowHNum;

        if (lmViewer.data.isMobile) {
          if (clientWidth > clientHeight) {
            //横屏
            $(' #contentDiv').parent().css('left', '');
            $(' #contentDiv').parent().css('padding-left', '0px');
            $(' #vertical').css('padding-left', '');
            document.getElementById("imageContainer").style.width =
              (document.body.clientWidth - $('#series').width()).toString() + 'px';
            var width = ($(' #imageContainer').width()).toString() + 'px';
            $(' #toolBar').css('width', width);
            totalHeight = document.body.clientHeight - $('#app-nav').height() - $('#tabs1').height() - 7;
          } else {
            //竖屏
            $(' #contentDiv').parent().css('left', '');
            $(' #contentDiv').parent().css('width', '');
            $(' #contentDiv').parent().css('padding-left', '');
            document.getElementById("imageContainer").style.width =
              document.body.clientWidth.toString() + 'px';
            var width = ($(' #imageContainer').width()).toString() + 'px';
            $(' #toolBar').css('width', width);
            totalHeight = document.body.clientHeight - $('#app-nav').height() - $('#tabs1').height() - $('#transverse').height() - 7;
          }
        }

        currCanvas.width = Math.floor(totalWidth / lmViewer.data.iWindowVNum);
        currCanvas.height = Math.floor(totalHeight / lmViewer.data.iWindowHNum);
        var iWidth = Math.floor(totalWidth / lmViewer.data.iWindowVNum);
        var iHeight = Math.floor(totalHeight / lmViewer.data.iWindowHNum);

        currCanvas.style.width = iWidth.toString() + 'px';
        currCanvas.style.height = iHeight.toString() + 'px';
        cornerstone.fitToWindow(element);
        if (lmViewer.data.isDesktop && lmViewer.data.imageType == "dicom") {
          var _plottingScaleObj = {
            element: element
          };
          lmViewer.fn.plottingScale(_plottingScaleObj);
        }

        cnt++;
      }

    }
    lmViewer.ui.resizeSeriesDiv();
  };
  ui.selectedViewportMarked = function (obj) {
    //element
    /**
     * version:1.0
     * date:2016-8-12
     * auth:tangzhengxiong
     * desc:
     *
     * */
    for (var i = 0; i < lmViewer.data.iWindowHNum; i++) {
      for (var j = 0; j < lmViewer.data.iWindowVNum; j++) {
        $('#image' + i.toString() + j.toString()).css('border', '1px solid #454444');
        $('#image' + i.toString() + j.toString()).css('border-color', '#000');
      }
    }
    var curElementId = obj.element.id;
    $('#' + curElementId).css('border-color', 'springgreen');
    if (obj.element == '') {
      $('#image00').css('border-color', 'springgreen');
    }
  };
  ui.hideButtons = function () {
    //hide the buttons on the left side
    document.getElementById('WindowLevelHead').style.display = "none";
    document.getElementById('WindowLevelLung').style.display = "none";
    document.getElementById('WindowLevelChest').style.display = "none";
    document.getElementById('WindowLevelAbdomen').style.display = "none";
    document.getElementById('WindowLevelBone').style.display = "none";
    document.getElementById('resetWWWL').style.display = "none";
  };
  ui.hideDiv = function () {
    $('#content').hide();
    $('#imageContainer').hide();
  };
  ui.displayDiv = function () {
    //关闭加载动画
    lmViewer.ui.hideLoading();
    $('#imageContainer').show();
    $('#content').show();
  };
  ui.resetImageContainer = function () {
    //reset imageContainer when show series by index
    $("#imageContainer").html('');
    var image = $("#slice-range").parent();
    image.html('');
    image.html('<input type="range" id="slice-range">');
  };
  ui.generateSeriesList = function () {
    //seriesArray, series
    //lmViewer.data.seriesArray, lmViewer.data.series
    /**
     * version:1.0
     * date:2016-8-12
     * auth:tangzhengxiong
     * desc:Generate the series list on the left panel
     *
     * */


    // 取序列列表用于显示（的内容）
    // Generate the series list on the left panel
    var sNum = lmViewer.data.series.length;

    // update by wujunbo
    // ------------------------------------屏幕序列横竖转换----------------------------------------------start

    var hh = '<div ><table class="table"><tbody>';
    var tr1 = '<div id="seriesList" style="height: 80px; overflow-y: scroll;">';
    //	var tr1 = '<tr>';
    // update by wujunbo
    // ------------------------------------屏幕序列横竖转换----------------------------------------------end
    var nav1 = '';
    nav1 += '<table class="table" style="background-color: #000;"><thead><tr>'
      + '<th style="width:72px;border: none;color:#E7E7E7;">影像</th>'
      + '<th style="width:48px;border: none;color:#E7E7E7;">数量</th>'
      + '</tr></thead><tbody>';

    for (var i = 0; i < sNum; i++) {
      var index = i + 1;
      var insNum = lmViewer.data.seriesArray[i].instance.length;
      var _showSeriesByIndexObj = {
        index: i
      };
      var middle = Math.floor(insNum / 2);
      var src = lmViewer.data.queryParams.hosturl + '/imagecloud/read?' + 'serverURL=' + lmViewer.data.queryParams.serverURL
        + '/wado&study=' + String(lmViewer.data.queryParams.studyUID) + '&series='
        + lmViewer.data.seriesArray[i].seriesUID + '&object='
        + lmViewer.data.seriesArray[i].instance[middle].sopIUID + '&rows=64';

      nav1 += '<tr>';
      nav1 += '<td colspan="2" style="color:white;text-align:center;border-color:white;">' + lmViewer.data.series[i].seriesDescription + '</td>';
      nav1 += '</tr>';
      nav1 += '<tr onclick="lmViewer.ctrl.showSeriesByIndex(' + i + ',' + insNum + ')">';

      nav1 += '<td style="width:72px;border:none;padding:2px">' + '<a><img class="img-rounded"'
        + 'onerror="imageNotfound();"' + ' src="' + src + '"'
        + ' id="series' + i + '"' + ' onclick="lmViewer.ctrl.showSeriesByIndex(' +
        i + ',' + insNum + ')"' + 'height="50"' + ' alt="' + '序列' + i
        + '"' + '/></a></td>';

      nav1 += '<td style="width:48px;color:#E7E7E7;vertical-align:middle;border:none;">' + insNum + '</td>';
      nav1 += '</tr>';

      // update by wujunbo
      // ------------------------------------屏幕序列横竖转换----------------------------------------------start
      tr1 += '<div style="width:72px;float: left">'
        + '<a><img class="img-rounded"'
        + 'onerror="imageNotfound();"'
        + ' src="'
        + src
        + '"'
        + ' id="series'
        + i
        + '"'
        + ' onclick="lmViewer.ctrl.showSeriesByIndex('
        + i + ',' + insNum

        + ')"'
        + 'height="50"'
        + ' alt="'
        + '序列'
        + i
        + '"'
        + '/></a><div style="text-align: center;width: 47px;color:#E7E7E7;">'
        + insNum + '</div></div>';
      // update by wujunbo
      // ------------------------------------屏幕序列横竖转换----------------------------------------------end

    }
    nav1 += '</tbody></table>';

    // update by wujunbo
    // ------------------------------------屏幕序列横竖转换----------------------------------------------start
    tr1 += '</div>';
    hh = tr1 + '</tbody></table></div>';
    // update by wujunbo
    // ------------------------------------屏幕序列横竖转换----------------------------------------------end
    $("#series").html(nav1);
    $("#series_transverse").html(hh);
    $("#series_transverse").width($("body").width() - 2);
    // 修改序列列表的样式（修改tab1中显示列表的样式）
    lmViewer.ui.changeTable();
  };
  ui.loadMobile = function () {
    //  Dynamically distinguish if javascript code for mobile should
    // be loaded.
    var oHead = document.getElementsByTagName('HEAD').item(0);
    var oScript = document.createElement("script");
    oScript.type = "text/javascript";
    oScript.src = '/imagecloud/js/touch-emulator.js';
    oHead.appendChild(oScript);
    $('#').hide();
    //   on the mobile screen, the two buttons can help you browse current series
    $('#pageUp').click(function (e) {
      var index = parseInt(lmViewer.data.curImageNum, 10);
      index = index - 1;
      index = index > -1 ? index : 0;
      var _readjustInstanceWWWLObj = {
        index: index,
        element: $('#image00').get(0)
      };
      lmViewer.ui.readjustInstanceWWWL(_readjustInstanceWWWLObj);
    });

    $('#pageDown').click(function (e) {
      var index = parseInt(lmViewer.data.curImageNum, 10);
      index = index + 1;
      index = index < lmViewer.data.seriesArray[lmViewer.data.sort].instance.length ? index : lmViewer.data.seriesArray[lmViewer.data.sort].instance.length - 1;
      var _readjustInstanceWWWLObj = {
        index: index,
        element: $('#image00').get(0)
      };
      lmViewer.ui.readjustInstanceWWWL(_readjustInstanceWWWLObj);
    });
  };
  ui.setToolbarPosition = function () {
    $('#liViewer').css('marginLeft', ((document.body.clientWidth - $('#toolbar-function').width()) / 2).toString() + 'px');//设置工具栏的位置
  };
  ui.enableWindowLevelToolClick = function (element) {
    if (lmViewer.data.queryParams.imageType === 'jpg' && lmViewer.data.iWindowVNum * lmViewer.data.iWindowHNum > 1) {
      lmViewer.ui.disableAllTools();
      lmViewer.ui.recoverButtonColor();
      lmViewer.ui.clearIconsColor("enableWindowLevelTool");
      $('#enableWindowLevelTool').css('background-color', 'gray');

      $('#imageContainer').addClass('adjust');
      lmViewer.data.contrastButtonPressed = true;
      if (lmViewer.data.isDesktop) {
        $(element).off('CornerstoneToolsMouseDrag');
      }
    } else {
      // Tool button event handlers that set the new active
      //			$('#modalProgressGlobal').modal('show');
      lmViewer.ui.disableAllTools();
      /*                lmViewer.ui.recoverButtonColor();
       lmViewer.ui.clearIconsColor("enableWindowLevelTool");
       $('#enableWindowLevelTool').css('background-color', 'gray');

       $('#imageContainer').addClass('adjust');
       lmViewer.data.contrastButtonPressed = true;
       var _getDicomObj = {
       element:element
       };
       var newImageId = lmViewer.fn.getDicom(_getDicomObj);

       cornerstone.loadAndCacheImage(newImageId).then(function (image) {
       cornerstone.displayImage(element, image);
       var viewport = cornerstone.getEnabledElement(element).viewport;
       viewport.voi.windowCenter = image.windowCenter;
       viewport.voi.windowWidth = image.windowWidth;

       // element 的行列索引
       var eleRowIndex = element.id.substring(
       element.id.indexOf('image') + 5,
       element.id.indexOf('image') + 6);
       var eleColumnIndex = element.id.substring(
       element.id.indexOf('image') + 6);
       eleRowIndex = parseInt(eleRowIndex);
       eleColumnIndex = parseInt(eleColumnIndex);
       var elementIdx = eleRowIndex * lmViewer.data.iWindowVNum + eleColumnIndex;

       lmViewer.data.globalWL[elementIdx] = image.windowCenter;
       lmViewer.data.globalWW[elementIdx] = image.windowWidth;
       lmViewer.data.initialWL[elementIdx] = lmViewer.data.globalWL[elementIdx];
       lmViewer.data.initialWW[elementIdx] = lmViewer.data.globalWW[elementIdx];

       cornerstone.setViewport(element, viewport);
       lmViewer.fn.triggerResize();
       });

       if (lmViewer.data.isDesktop === true) {
       // record the current window width and center, used on PC
       $(element).off('CornerstoneToolsMouseDrag');
       $(element).on('CornerstoneToolsMouseDrag', mouseDragWWWL);
       cornerstoneTools.wwwc.activate(element, 1);
       }
       if (lmViewer.data.isMobile) {
       // record the current window width and center
       $('#image00').on('CornerstoneToolsTouchDrag', function (e, eventData) {
       cornerstoneTools.wwwcTouchDrag.activate(element);

       var elementIdx = parseInt(lmViewer.data.sort);
       // get the window width from the viewport
       var startIndexOfWW = $('#mrbottomleft' + lmViewer.data.sort.toString()).html().indexOf("WW") + 3;
       var endIndexOfWW = $('#mrbottomleft' + lmViewer.data.sort.toString()).html().indexOf("&nbsp");
       var newWW = $('#mrbottomleft' + lmViewer.data.sort.toString()).html().substring(startIndexOfWW, endIndexOfWW);
       lmViewer.data.globalWW[elementIdx] = parseInt(newWW, 10);

       // get the window center from the viewport
       var startIndexOfWL = $('#mrbottomleft' + lmViewer.data.sort.toString()).html().indexOf("WL") + 3;
       var endIndexOfWL = $('#mrbottomleft' + lmViewer.data.sort.toString()).html().indexOf("<br>Zoom");
       var newWL = $('#mrbottomleft' + lmViewer.data.sort.toString()).html().substring(startIndexOfWL, endIndexOfWL);
       lmViewer.data.globalWL[elementIdx] = parseInt(newWL, 10);
       });
       }*/
    }
  };
  ui.disableAllTools = function (element) {
    if (lmViewer.data.isDesktop === true) {
      cornerstoneTools.wwwc.disable(element);
      $(element).off('CornerstoneToolsMouseDrag', lmViewer.ui.mouseDragWWWL);
      cornerstoneTools.pan.activate(element, 2); // 2 is middle mouse button
      cornerstoneTools.zoom.activate(element, 4); // 4 is right mouse button
      cornerstoneTools.probe.deactivate(element, 1);
      cornerstoneTools.length.deactivate(element, 1);
      cornerstoneTools.ellipticalRoi.deactivate(element, 1);
      cornerstoneTools.rectangleRoi.deactivate(element, 1);
      cornerstoneTools.simpleAngle.deactivate(element, 1);
      cornerstoneTools.highlight.deactivate(element, 1);
      cornerstoneTools.freehand.deactivate(element, 1);
      cornerstoneTools.wwwcRegion.disable(element);

      $('#imageContainer').removeClass('adjust');
      $('#imageContainer').removeClass('move');
      $('#imageContainer').removeClass('zoom');
    }
    if (lmViewer.data.isMobile === true) {
      cornerstoneTools.panTouchDrag.deactivate(element);
      cornerstoneTools.rotateTouchDrag.deactivate(element);
      cornerstoneTools.rotateTouch.disable(element);
      cornerstoneTools.ellipticalRoiTouch.deactivate(element);
      cornerstoneTools.simpleAngleTouch.deactivate(element);
      cornerstoneTools.rectangleRoiTouch.deactivate(element);
      cornerstoneTools.lengthTouch.deactivate(element);
      cornerstoneTools.probeTouch.deactivate(element);
      cornerstoneTools.zoomTouchDrag.deactivate(element);
      cornerstoneTools.wwwcTouchDrag.deactivate(element);
      cornerstoneTools.stackScrollTouchDrag.deactivate(element);
      $('#image00').off('CornerstoneToolsTouchDrag');
    }
  }

  ui.clearIconsColor = function (iconID) {
    $("#enableWindowLevelTool span").css("color", "#505050");
    $("#zoom span").css("color", "#505050");
    $("#enableLength span").css("color", "#505050");
    $("#probe span").css("color", "#505050");
    $("#circleroi span").css("color", "#505050");
    $("#ShowAnnotation span").css("color", "#505050");
    $("#UnShowAnnotation span").css("color", "#505050");
    $("#saveImg span").css("color", "#505050");
    $("#rectangleroi span").css("color", "#505050");
    $("#angle span").css("color", "#505050");
    $("#wwwc span").css("color", "#505050");
    $("#pan span").css("color", "#505050");
    $("#" + iconID + " span").css("color", "#38c500");
  };

  ui.mouseWheel = function (e) {
    $('#imageContainer').removeClass('adjust');
    $('#enableWindowLevelTool').css('background-color', '#000');
    lmViewer.data.contrastButtonPressed = false;

    disableAllTools();
    lmViewer.ui.recoverButtonColor();
    cornerstoneTools.wwwc.deactivate(element, 1);

    for (var i = 0; i < lmViewer.data.iWindowHNum * lmViewer.data.iWindowVNum; i++) {
      if (i >= lmViewer.data.seriesArray.length) {
        break;
      }
      // find the row and column indexes of this element
      var eleRowIdx = parseInt(i / lmViewer.data.iWindowVNum);
      var eleColumnIdx = parseInt(i - eleRowIdx * lmViewer.data.iWindowVNum);
      var curElement = $('#image' + eleRowIdx.toString() + eleColumnIdx.toString()).get(0);
      if (curElement == undefined) {
        continue;
      }

      $(curElement).off('CornerstoneToolsMouseDrag');
      var _obj = {
        element: curElement,
        image: undefined
      };
      var seriesNum = lmViewer.fn.getImgIndex(_obj).series;

      if (lmViewer.data.groupIndex[i] == lmViewer.data.groupIndex[obj.cnt]) {
        // if(synchrSwitch == false) {
        // 	if(i != cnt) continue;
        // }
        // get the scale of every window which will display the next image
        var enabledElement = cornerstone.getEnabledElement(curElement);

        // delete the last image
        var canvas = enabledElement.canvas;
        var context = canvas.getContext('2d');
        context.clearRect(0, 0, canvas.width, canvas.height);
        context.transform(1, 0, 0, 1, 0, 0);
        /*
         context.font = 'italic bold 40px Arial';
         context.textAlign = 'center';
         context.textBaseline = 'middle';
         var linearGrad = context.createLinearGradient(canvas.width/4,canvas.height/2,
         3*canvas.width/4,canvas.height/2);
         linearGrad.addColorStop(0.0,'red');
         linearGrad.addColorStop(0.5,'yellow');
         linearGrad.addColorStop(1.0,'green');
         context.strokeStyle = linearGrad;
         context.strokeText('loading...',canvas.width/2,canvas.height/2);
         */


        context.textAlign = 'left';
        context.textBaseline = 'top';
        context.strokeStyle = '#DF5326';
        context.font = 'bold 24px arial';
        context.fillStyle = 'orange';
        //todo tangzhengxiong 2016/9/19
        // context.fillText("载入中...", canvas.width / 2 - 50, canvas.height / 2 + 12);
        //lmViewer.ui.hideDiv();
        lmViewer.ui.showLoading();
        var imgIndex = lmViewer.fn.getImgIndex(_obj);
        var row = parseInt(lmViewer.data.tagArray[imgIndex.series][imgIndex.instance].rows);
        var rowScale = 1;
        if (cornerstone.getImage(curElement).data != undefined) { // DICOM
          rowScale = row / 512;
        }
        var viewport = cornerstone.getEnabledElement(curElement).viewport;
        lmViewer.data.imageScale[i] = (viewport.scale * rowScale).toFixed(2);
        lmViewer.data.imageScale[i] = (rowScale).toFixed(2);
        //todo
        // display the next image of the current window and its synchronized windows
        if (e.originalEvent.deltaY > 0) {
          if (lmViewer.data.wheelInstanceNum[i] + 1 < lmViewer.data.seriesArray[seriesNum].instance.length) {
            lmViewer.data.wheelInstanceNum[i]++;
          }
        } else if (e.originalEvent.deltaY < 0) {
          if (lmViewer.data.wheelInstanceNum[i] - 1 > -1) {
            lmViewer.data.wheelInstanceNum[i]--;
          }
        }
        //	 if(getDicomButtonPressed){
        //		selectNewImage(wheelInstanceNum[i]);
        //	 } else {
        var _readjustInstanceWWWLObj = {
          index: lmViewer.data.wheelInstanceNum[i],
          element: curElement
        };
        lmViewer.fn.readjustInstanceWWWL(_readjustInstanceWWWLObj);
        //	 }

        var endIdx = curElement.children[2].innerHTML.indexOf('Img：') + 4;
        var startIdx = curElement.children[2].innerHTML.indexOf('/');
        var displatText = curElement.children[2].innerHTML.substring(0, endIdx) +
          (lmViewer.data.wheelInstanceNum[i] + 1).toString() +
          curElement.children[2].innerHTML.substring(startIdx);
        curElement.children[2].innerHTML = displatText;
        if (lmViewer.data.referenceLineButtonPressed) {
          lmViewer.fn.updateAllImageDisplayed();
          var _drawReferenceLineObj = {
            element: element
          };
          lmViewer.fn.drawReferenceLine(_drawReferenceLineObj);
        }
      }
    }
  };

  ui.mouseDragWWWL = function (e, eventData) {
    cornerstone.imageCache.purgeCache();
    for (var eleRowIndex = 0; eleRowIndex < lmViewer.data.iWindowHNum; eleRowIndex++) {
      for (var eleColumnIndex = 0; eleColumnIndex < lmViewer.data.iWindowVNum; eleColumnIndex++) {
        var elementIdx = 0;

        if ('' != lmViewer.data.sort && 1 == lmViewer.data.iWindowVNum && 1 == lmViewer.data.iWindowHNum) {
          elementIdx = parseInt(lmViewer.data.sort);
        } else {
          elementIdx = eleRowIndex * lmViewer.data.iWindowVNum + eleColumnIndex;
        }
        if (elementIdx < lmViewer.data.iSeriesNum) {
          // get the window width from the viewport
          var startIndexOfWW = $('#mrbottomleft' + elementIdx.toString()).html().indexOf("WW") + 3;
          var endIndexOfWW = $('#mrbottomleft' + elementIdx.toString()).html().indexOf("&nbsp");
          var newWW = $('#mrbottomleft' + elementIdx.toString()).html().substring(startIndexOfWW, endIndexOfWW);
          lmViewer.data.globalWW[elementIdx] = parseInt(newWW, 10);
          if (lmViewer.data.globalWW[elementIdx] <= 1) {
            lmViewer.data.globalWW[elementIdx] = 1;
          }

          // get the window center from the viewport
          var startIndexOfWL = $('#mrbottomleft' + elementIdx.toString()).html().indexOf("WL") + 3;
          var endIndexOfWL = $('#mrbottomleft' + elementIdx.toString()).html().indexOf("<br>Zoom");
          var newWL = $('#mrbottomleft' + elementIdx.toString()).html().substring(startIndexOfWL, endIndexOfWL);
          lmViewer.data.globalWL[elementIdx] = parseInt(newWL, 10);
        }
      }
    }
  };

  ui.enableScrollStackClick = function () {
    humane.log("滑动滚动浏览");
    disableAllTools();
    lmViewer.ui.recoverButtonColor();
    $('#enableScrollStack').css('background-color', 'gray');

    if (lmViewer.data.isDesktop === true) {
      cornerstoneTools.stackScrollWheel.activate(element);
    }
    if (lmViewer.data.isMobile === true) {
      // get the scale of every window which will display the next image
      var curElement = $('#image00').get(0);
      var enabledElement = cornerstone.getEnabledElement(curElement);
      var _obj = {
        element: curElement,
        image: undefined
      };
      var imgIndex = lmViewer.fn.getImgIndex(_obj);
      var row = parseInt(lmViewer.data.tagArray[imgIndex.series][imgIndex.instance].rows);
      var rowScale = 1;
      if (cornerstone.getImage(curElement).data != undefined) { // DICOM
        rowScale = row / 512;
      }
      var viewport = cornerstone.getEnabledElement(curElement).viewport;
      lmViewer.data.imageScale[0] = (viewport.scale * rowScale).toFixed(2);

      $('#image00').on('CornerstoneToolsTouchDrag', function (e, eventData) {
        if (eventData.deltaPoints.image.y > 0) {
          if (lmViewer.data.curImageNum + 1 < lmViewer.data.seriesArray[sort].instance.length) {
            lmViewer.data.curImageNum++;
          }
          //              if(contrastButtonPressed && navigator.userAgent.indexOf( 'iPhone') == -1){
          var _readjustInstanceWWWLObj = {
            index: lmViewer.data.curImageNum,
            element: curElement
          };
          lmViewer.fn.readjustInstanceWWWL(_readjustInstanceWWWLObj);
          //             } else {
          //                   selectNewImage(curImageNum);
          //             }

        } else if (eventData.deltaPoints.image.y < 0) {
          if (lmViewer.data.curImageNum - 1 > -1) {
            lmViewer.data.curImageNum--;
          }
          //              if(contrastButtonPressed && navigator.userAgent.indexOf( 'iPhone') == -1){
          var _readjustInstanceWWWLObj = {
            index: lmViewer.data.curImageNum,
            element: curElement
          };
          lmViewer.fn.readjustInstanceWWWL(_readjustInstanceWWWLObj);
          //             } else {
          //                   selectNewImage(curImageNum);
          //             }
        }
      });
      //          cornerstoneTools.stackScrollTouchDrag.activate(element);
    }
  };

  ui.panClick = function () {
    disableAllTools();
    lmViewer.ui.recoverButtonColor();
    $('#pan').css('background-color', 'gray');
    clearIconsColor("pan");
    $('#imageContainer').addClass('move');

    if (lmViewer.data.isDesktop === true) {
      cornerstoneTools.pan.activate(element, 3);
    }
    if (lmViewer.data.isMobile === true) {
      cornerstoneTools.panTouchDrag.activate(element);
    }
  };

  ui.zoomClick = function () {
    disableAllTools();
    lmViewer.ui.recoverButtonColor();
    clearIconsColor("zoom");
    $('#zoom').css('background-color', 'gray');

    $('#imageContainer').addClass('zoom');
    if (lmViewer.data.isDesktop === true) {
      cornerstoneTools.zoom.activate(element,
        5);
      // 5 means left mouse button and right
      // mouse button
    }
    if (lmViewer.data.isMobile === true) {
      cornerstoneTools.zoomTouchDrag.activate(element);
    }
  };

  ui.RotateLeftClick = function () {
    disableAllTools();
    lmViewer.ui.recoverButtonColor();
    $('#RotateLeft').css('background-color', 'gray');

    var enabledElement = cornerstone
      .getEnabledElement(element);
    enabledElement.viewport.rotation = enabledElement.viewport.rotation - 90;
    cornerstone.updateImage(element);
  };

  ui.RotateRightClick = function () {
    disableAllTools();
    lmViewer.ui.recoverButtonColor();
    $('#RotateRight').css('background-color', 'gray');

    var enabledElement = cornerstone
      .getEnabledElement(element);
    enabledElement.viewport.rotation = enabledElement.viewport.rotation + 90;
    cornerstone.updateImage(element);
  };

  ui.hFlipClick = function (e) {
    lmViewer.ui.recoverButtonColor();
    $('#hFlip').css('background-color', 'gray');

    var viewport = cornerstone.getViewport(element);
    viewport.hflip = !viewport.hflip;
    cornerstone.setViewport(element, viewport);
  };

  ui.vFlipClick = function (e) {
    lmViewer.ui.recoverButtonColor();
    $('#vFlip').css('background-color', 'gray');

    var viewport = cornerstone.getViewport(element);
    viewport.vflip = !viewport.vflip;
    cornerstone.setViewport(element, viewport);
  };

  ui.resetClick = function () {
    disableAllTools();
    lmViewer.ui.recoverButtonColor();
    $('#reset').css('background-color', 'gray');

    cornerstone.fitToWindow(element);
    var viewport = cornerstone.getViewport(element);
    if (viewport.invert === true) {
      viewport.invert = false;
    }
    viewport.vflip = false;
    viewport.hflip = false;
    cornerstone.setViewport(element, viewport);

    cornerstoneTools.clearToolState(element, "length");
    cornerstoneTools.clearToolState(element, "probe");
    cornerstoneTools.clearToolState(element, "ellipticalRoi");
    cornerstoneTools.clearToolState(element, "rectangleRoi");
    cornerstoneTools.clearToolState(element, "simpleAngle");
    cornerstoneTools.clearToolState(element, "wwwcRegion");//局部对比度
    //复原图像翻转
    var enabledElement = cornerstone.getEnabledElement(element);
    enabledElement.viewport.rotation = 0;
    cornerstoneTools.clearToolState(element, "wwwc");
    cornerstone.updateImage(element);
  };

  ui.enableLengthClick = function () {
    disableAllTools();
    lmViewer.ui.recoverButtonColor();
    clearIconsColor("enableLength");
    $('#enableLength').css('background-color', 'gray');

    // get the scale of every window which will display the next image
    var enabledElement = cornerstone.getEnabledElement(element);
    var _obj = {
      element: element,
      image: undefined
    };
    var imgIndex = lmViewer.fn.getImgIndex(_obj);
    var row = parseInt(lmViewer.data.tagArray[imgIndex.series][imgIndex.instance].rows);
    var rowScale = 1;
    if (cornerstone.getImage(element).data == undefined) { // JPG
      rowScale = 512 / row;
    }
    var _getDicomObj = {
      element: element
    };
    var newImageId = lmViewer.fn.getDicom(_getDicomObj);
    cornerstone.loadAndCacheImage(newImageId).then(function (image) {
      cornerstone.displayImage(element, image);
      var viewport = cornerstone.getEnabledElement(element).viewport;

      // element 的行列索引
      var eleRowIndex = element.id.substring(
        element.id.indexOf('image') + 5,
        element.id.indexOf('image') + 6);
      var eleColumnIndex = element.id.substring(
        element.id.indexOf('image') + 6);
      eleRowIndex = parseInt(eleRowIndex);
      eleColumnIndex = parseInt(eleColumnIndex);
      var elementIdx = 0;
      if (lmViewer.data.iWindowVNum * lmViewer.data.iWindowHNum == 1) {
        elementIdx = lmViewer.data.sort;
      } else {
        elementIdx = eleRowIndex * lmViewer.data.iWindowVNum + eleColumnIndex;
      }

      lmViewer.data.initialWL[elementIdx] = image.windowCenter;
      lmViewer.data.initialWW[elementIdx] = image.windowWidth;
      if (lmViewer.data.globalWW[elementIdx] != undefined && lmViewer.data.globalWL[elementIdx] != undefined) {
        viewport.voi.windowCenter = lmViewer.data.globalWL[elementIdx];
        viewport.voi.windowWidth = lmViewer.data.globalWW[elementIdx];
      } else {
        viewport.voi.windowCenter = lmViewer.data.initialWL[elementIdx];
        viewport.voi.windowWidth = lmViewer.data.initialWW[elementIdx];
      }

      lmViewer.data.imageScale[obj.cnt] = parseFloat((viewport.scale * rowScale).toFixed(2));
      viewport.scale = lmViewer.data.imageScale[obj.cnt];

      cornerstone.setViewport(element, viewport);
    });

    if (lmViewer.data.isDesktop === true) {
      cornerstoneTools.length.activate(element, 1);
    }
    if (lmViewer.data.isMobile === true) {
      cornerstoneTools.lengthTouch.activate(element);
    }

  };

  ui.probeClick = function () {
    //		$('#modalProgressGlobal').modal('show');
    disableAllTools();
    lmViewer.ui.recoverButtonColor();
    clearIconsColor("probe");
    $('#probe').css('background-color', 'gray');

    // get the scale of every window which will display the next image
    var enabledElement = cornerstone.getEnabledElement(element);
    var _obj = {
      element: element,
      image: undefined
    };
    var imgIndex = lmViewer.fn.getImgIndex(_obj);
    var row = parseInt(lmViewer.data.tagArray[imgIndex.series][imgIndex.instance].rows);
    var rowScale = 1;
    if (cornerstone.getImage(element).data == undefined) { // JPG
      rowScale = 512 / row;
    }

    var _getDicomObj = {
      element: element
    };
    var newImageId = lmViewer.fn.getDicom(_getDicomObj);
    cornerstone.loadAndCacheImage(newImageId).then(function (image) {
      cornerstone.displayImage(element, image);
      var viewport = cornerstone.getEnabledElement(element).viewport;

      // element 的行列索引
      var eleRowIndex = element.id.substring(
        element.id.indexOf('image') + 5,
        element.id.indexOf('image') + 6);
      var eleColumnIndex = element.id.substring(
        element.id.indexOf('image') + 6);
      eleRowIndex = parseInt(eleRowIndex);
      eleColumnIndex = parseInt(eleColumnIndex);
      var elementIdx = 0;
      if (lmViewer.data.iWindowVNum * lmViewer.data.iWindowHNum == 1) {
        elementIdx = lmViewer.data.sort;
      } else {
        elementIdx = eleRowIndex * lmViewer.data.iWindowVNum + eleColumnIndex;
      }

      lmViewer.data.initialWL[elementIdx] = image.windowCenter;
      lmViewer.data.initialWW[elementIdx] = image.windowWidth;
      if (lmViewer.data.globalWW[elementIdx] != undefined && lmViewer.data.globalWL[elementIdx] != undefined) {
        viewport.voi.windowCenter = lmViewer.data.globalWL[elementIdx];
        viewport.voi.windowWidth = lmViewer.data.globalWW[elementIdx];
      } else {
        viewport.voi.windowCenter = lmViewer.data.initialWL[elementIdx];
        viewport.voi.windowWidth = lmViewer.data.initialWW[elementIdx];
      }

      lmViewer.data.imageScale[obj.cnt] = parseFloat((viewport.scale * rowScale).toFixed(2));
      viewport.scale = lmViewer.data.imageScale[obj.cnt];

      cornerstone.setViewport(element, viewport);
    });
    if (lmViewer.data.isDesktop === true) {
      cornerstoneTools.probe.activate(element, 1);
    }
    if (lmViewer.data.isMobile === true) {
      cornerstoneTools.probeTouch.activate(element);
    }
  };

  ui.circleroiClick = function () {
    disableAllTools();
    lmViewer.ui.recoverButtonColor();
    $('#circleroi').css('background-color', 'gray');
    clearIconsColor("circleroi");

    // get the scale of every window which will display the next image
    var enabledElement = cornerstone.getEnabledElement(element);
    var _obj = {
      element: element,
      image: undefined
    };
    var imgIndex = lmViewer.fn.getImgIndex(_obj);
    var row = parseInt(lmViewer.data.tagArray[imgIndex.series][imgIndex.instance].rows);
    var rowScale = 1;
    if (cornerstone.getImage(element).data == undefined) { // JPG
      rowScale = 512 / row;
    }
    var _getDicomObj = {
      element: element
    };
    var newImageId = lmViewer.fn.getDicom(_getDicomObj);
    cornerstone.loadAndCacheImage(newImageId).then(function (image) {
      cornerstone.displayImage(element, image);
      var viewport = cornerstone.getEnabledElement(element).viewport;

      // element 的行列索引
      var eleRowIndex = element.id.substring(
        element.id.indexOf('image') + 5,
        element.id.indexOf('image') + 6);
      var eleColumnIndex = element.id.substring(
        element.id.indexOf('image') + 6);
      eleRowIndex = parseInt(eleRowIndex);
      eleColumnIndex = parseInt(eleColumnIndex);
      var elementIdx = 0;
      if (lmViewer.data.iWindowVNum * lmViewer.data.iWindowHNum == 1) {
        elementIdx = lmViewer.data.sort;
      } else {
        elementIdx = eleRowIndex * lmViewer.data.iWindowVNum + eleColumnIndex;
      }

      lmViewer.data.initialWL[elementIdx] = image.windowCenter;
      lmViewer.data.initialWW[elementIdx] = image.windowWidth;
      if (lmViewer.data.globalWW[elementIdx] != undefined && lmViewer.data.globalWL[elementIdx] != undefined) {
        viewport.voi.windowCenter = lmViewer.data.globalWL[elementIdx];
        viewport.voi.windowWidth = lmViewer.data.globalWW[elementIdx];
      } else {
        viewport.voi.windowCenter = lmViewer.data.initialWL[elementIdx];
        viewport.voi.windowWidth = lmViewer.data.initialWW[elementIdx];
      }

      lmViewer.data.imageScale[obj.cnt] = parseFloat((viewport.scale * rowScale).toFixed(2));
      viewport.scale = lmViewer.data.imageScale[obj.cnt];

      cornerstone.setViewport(element, viewport);
    });

    if (lmViewer.data.isDesktop === true) {
      cornerstoneTools.ellipticalRoi.activate(element, 1);
    }
    if (lmViewer.data.isMobile === true) {
      cornerstoneTools.ellipticalRoiTouch.activate(element);
    }

  };

  ui.rectangleroiClick = function () {
    disableAllTools();
    lmViewer.ui.recoverButtonColor();
    $('#rectangleroi').css('background-color', 'gray');

    // get the scale of every window which will display the next image
    var enabledElement = cornerstone.getEnabledElement(element);
    var _obj = {
      element: element,
      image: undefined
    };
    var imgIndex = lmViewer.fn.getImgIndex(_obj);
    var row = parseInt(lmViewer.data.tagArray[imgIndex.series][imgIndex.instance].rows);
    var rowScale = 1;
    if (cornerstone.getImage(element).data == undefined) { // JPG
      rowScale = 512 / row;
    }

    var _getDicomObj = {
      element: element
    };
    var newImageId = lmViewer.fn.getDicom(_getDicomObj);
    cornerstone.loadAndCacheImage(newImageId).then(function (image) {
      cornerstone.displayImage(element, image);
      var viewport = cornerstone.getEnabledElement(element).viewport;

      // element 的行列索引
      var eleRowIndex = element.id.substring(
        element.id.indexOf('image') + 5,
        element.id.indexOf('image') + 6);
      var eleColumnIndex = element.id.substring(
        element.id.indexOf('image') + 6);
      eleRowIndex = parseInt(eleRowIndex);
      eleColumnIndex = parseInt(eleColumnIndex);
      var elementIdx = 0;
      if (lmViewer.data.iWindowVNum * lmViewer.data.iWindowHNum == 1) {
        elementIdx = lmViewer.data.sort;
      } else {
        elementIdx = eleRowIndex * lmViewer.data.iWindowVNum + eleColumnIndex;
      }

      lmViewer.data.initialWL[elementIdx] = image.windowCenter;
      lmViewer.data.initialWW[elementIdx] = image.windowWidth;
      if (lmViewer.data.globalWW[elementIdx] != undefined && lmViewer.data.globalWL[elementIdx] != undefined) {
        viewport.voi.windowCenter = lmViewer.data.globalWL[elementIdx];
        viewport.voi.windowWidth = lmViewer.data.globalWW[elementIdx];
      } else {
        viewport.voi.windowCenter = lmViewer.data.initialWL[elementIdx];
        viewport.voi.windowWidth = lmViewer.data.initialWW[elementIdx];
      }

      lmViewer.data.imageScale[obj.cnt] = parseFloat((viewport.scale * rowScale).toFixed(2));
      viewport.scale = lmViewer.data.imageScale[obj.cnt];

      cornerstone.setViewport(element, viewport);
    });

    if (lmViewer.data.isDesktop === true) {
      cornerstoneTools.rectangleRoi.activate(element, 1);
    }
    if (lmViewer.data.isMobile === true) {
      cornerstoneTools.rectangleRoiTouch.activate(element);
    }
  };

  ui.angleClick = function () {
    disableAllTools();
    lmViewer.ui.recoverButtonColor();
    $('#angle').css('background-color', 'gray');
    clearIconsColor("angle");

    if (lmViewer.data.isDesktop === true) {
      cornerstoneTools.simpleAngle.activate(element, 1);
    }
    if (lmViewer.data.isMobile === true) {
      cornerstoneTools.simpleAngleTouch.activate(element);
    }
  };

  ui.UnShowAnnotationClick = function (e) {
    disableAllTools();
    lmViewer.ui.recoverButtonColor();
    $('#UnShowAnnotation').css('background-color', 'gray');

    cornerstoneTools.probe.disable(element);
    cornerstoneTools.rectangleRoi.disable(element);
    cornerstoneTools.ellipticalRoi.disable(element);
    cornerstoneTools.simpleAngle.disable(element);
    cornerstoneTools.lengthTouch.disable(element);
  };

  ui.ShowAnnotationClick = function (e) {
    disableAllTools();
    lmViewer.ui.recoverButtonColor();
    $('#ShowAnnotation').css('background-color', 'gray');

    cornerstoneTools.probe.enable(element);
    cornerstoneTools.rectangleRoi.enable(element);
    cornerstoneTools.ellipticalRoi.enable(element);
    cornerstoneTools.simpleAngle.enable(element);
    cornerstoneTools.lengthTouch.enable(element);
  };

  ui.wwwcClick = function (e) {
    disableAllTools();
    lmViewer.ui.recoverButtonColor();
    $('#wwwc').css('background-color', 'gray');
    clearIconsColor("wwwc");

    if (lmViewer.data.isDesktop === true) {
      cornerstoneTools.wwwcRegion.activate(element, 1);
    }
  };

  ui.invertClick = function (e) {
    lmViewer.ui.recoverButtonColor();
    $('#invert').css('background-color', 'gray');

    var viewport = cornerstone.getViewport(element);
    if (viewport.invert === true) {
      viewport.invert = false;
    } else {
      viewport.invert = true;
    }
    cornerstone.setViewport(element, viewport);
  };

  ui.WindowLevelHeadClick = function (e) {
    disableAllTools();
    lmViewer.ui.recoverButtonColor();
    $('#WindowLevelHead').css('background-color', 'gray');
    $('#imageContainer').addClass('adjust');

    lmViewer.data.contrastButtonPressed = true;
    var _getDicomObj = {
      element: element
    };
    var newImageId = lmViewer.fn.getDicom(_getDicomObj);

    cornerstone.loadAndCacheImage(newImageId).then(function (image) {
      cornerstone.displayImage(element, image);
      var viewport = cornerstone.getEnabledElement(element).viewport;
      var _obj = {
        element: element,
        image: undefined
      };
      var seriesNum = lmViewer.fn.getImgIndex(_obj).series;
      lmViewer.data.initialWL[seriesNum] = image.windowCenter;
      lmViewer.data.initialWW[seriesNum] = image.windowWidth;

      viewport.voi.windowCenter = 35;
      viewport.voi.windowWidth = 80;

      // element 的行列索引
      var eleRowIndex = element.id.substring(
        element.id.indexOf('image') + 5,
        element.id.indexOf('image') + 6);
      var eleColumnIndex = element.id.substring(
        element.id.indexOf('image') + 6);
      eleRowIndex = parseInt(eleRowIndex);
      eleColumnIndex = parseInt(eleColumnIndex);

      var elementIdx = 0;
      if ('' != lmViewer.data.sort && 1 == lmViewer.data.iWindowVNum && 1 == lmViewer.data.iWindowHNum) {
        elementIdx = parseInt(lmViewer.data.sort);
      } else {
        elementIdx = eleRowIndex * lmViewer.data.iWindowVNum + eleColumnIndex;
      }

      lmViewer.data.globalWL[elementIdx] = 35;
      lmViewer.data.globalWW[elementIdx] = 80;

      cornerstone.setViewport(element, viewport);
      lmViewer.fn.triggerResize();
      $('#modalProgressGlobal').modal('hide');
    });

    cornerstoneTools.wwwc.activate(element, 1);
    $(element).off('CornerstoneToolsMouseDrag');
    $(element).on('CornerstoneToolsMouseDrag', mouseDragWWWL);

    // record the current window width and center, used on PC

    //							var viewport = cornerstone.getViewport(element);
    //							viewport.voi.windowWidth = 80;
    //							viewport.voi.windowCenter = 35;
    //							cornerstone.setViewport(element, viewport);
  };

  ui.WindowLevelLungClick = function (e) {
    disableAllTools();
    lmViewer.ui.recoverButtonColor();
    $('#WindowLevelLung').css('background-color', 'gray');
    //		$('#modalProgressGlobal').modal('show');
    $('#imageContainer').addClass('adjust');

    lmViewer.data.contrastButtonPressed = true;
    var _getDicomObj = {
      element: element
    };
    var newImageId = lmViewer.fn.getDicom(_getDicomObj);

    cornerstone.loadAndCacheImage(newImageId).then(function (image) {
      cornerstone.displayImage(element, image);
      var viewport = cornerstone.getEnabledElement(element).viewport;
      var _obj = {
        element: element,
        image: undefined
      };
      var seriesNum = lmViewer.fn.getImgIndex(_obj).series;
      lmViewer.data.initialWL[seriesNum] = image.windowCenter;
      lmViewer.data.initialWW[seriesNum] = image.windowWidth;

      viewport.voi.windowCenter = -500;
      viewport.voi.windowWidth = 1500;

      // element 的行列索引
      var eleRowIndex = element.id.substring(
        element.id.indexOf('image') + 5,
        element.id.indexOf('image') + 6);
      var eleColumnIndex = element.id.substring(
        element.id.indexOf('image') + 6);
      eleRowIndex = parseInt(eleRowIndex);
      eleColumnIndex = parseInt(eleColumnIndex);

      var elementIdx = 0;
      if ('' != lmViewer.data.sort && 1 == lmViewer.data.iWindowVNum && 1 == lmViewer.data.iWindowHNum) {
        elementIdx = parseInt(lmViewer.data.sort);
      } else {
        elementIdx = eleRowIndex * lmViewer.data.iWindowVNum + eleColumnIndex;
      }

      lmViewer.data.globalWL[elementIdx] = -500;
      lmViewer.data.globalWW[elementIdx] = 1500;

      cornerstone.setViewport(element, viewport);
      lmViewer.fn.triggerResize();
      $('#modalProgressGlobal').modal('hide');
    });

    cornerstoneTools.wwwc.activate(element, 1);
    $(element).off('CornerstoneToolsMouseDrag');
    $(element).on('CornerstoneToolsMouseDrag', mouseDragWWWL);

    //							var viewport = cornerstone.getViewport(element);
    //							viewport.voi.windowWidth = 800;
    //							viewport.voi.windowCenter = -700;
    //							cornerstone.setViewport(element, viewport);
  };

  ui.WindowLevelChestClick = function (e) {
    disableAllTools();
    lmViewer.ui.recoverButtonColor();
    $('#WindowLevelChest').css('background-color', 'gray');
    //			$('#modalProgressGlobal').modal('show');
    $('#imageContainer').addClass('adjust');

    lmViewer.data.contrastButtonPressed = true;
    var _getDicomObj = {
      element: element
    };
    var newImageId = lmViewer.fn.getDicom(_getDicomObj);

    cornerstone.loadAndCacheImage(newImageId).then(function (image) {
      cornerstone.displayImage(element, image);
      var viewport = cornerstone.getEnabledElement(element).viewport;
      var _obj = {
        element: element,
        image: undefined
      };
      var seriesNum = lmViewer.fn.getImgIndex(_obj).series;
      lmViewer.data.initialWL[seriesNum] = image.windowCenter;
      lmViewer.data.initialWW[seriesNum] = image.windowWidth;

      viewport.voi.windowCenter = 50;
      viewport.voi.windowWidth = 500;

      // element 的行列索引
      var eleRowIndex = element.id.substring(
        element.id.indexOf('image') + 5,
        element.id.indexOf('image') + 6);
      var eleColumnIndex = element.id.substring(
        element.id.indexOf('image') + 6);
      eleRowIndex = parseInt(eleRowIndex);
      eleColumnIndex = parseInt(eleColumnIndex);

      var elementIdx = 0;
      if ('' != lmViewer.data.sort && 1 == lmViewer.data.iWindowVNum && 1 == lmViewer.data.iWindowHNum) {
        elementIdx = parseInt(lmViewer.data.sort);
      } else {
        elementIdx = eleRowIndex * lmViewer.data.iWindowVNum + eleColumnIndex;
      }

      lmViewer.data.globalWL[elementIdx] = 50;
      lmViewer.data.globalWW[elementIdx] = 500;

      cornerstone.setViewport(element, viewport);
      lmViewer.fn.triggerResize();
      $('#modalProgressGlobal').modal('hide');
    });

    cornerstoneTools.wwwc.activate(element, 1);
    $(element).off('CornerstoneToolsMouseDrag');
    $(element).on('CornerstoneToolsMouseDrag', mouseDragWWWL);

    //							var viewport = cornerstone.getViewport(element);
    //							viewport.voi.windowWidth = 500;
    //							viewport.voi.windowCenter = 50;
    //							cornerstone.setViewport(element, viewport);
  };

  ui.WindowLevelAbdomenClick = function (e) {
    disableAllTools();
    lmViewer.ui.recoverButtonColor();
    $('#WindowLevelAbdomen').css('background-color', 'gray');
    //				$('#modalProgressGlobal').modal('show');
    $('#imageContainer').addClass('adjust');

    lmViewer.data.contrastButtonPressed = true;
    var _getDicomObj = {
      element: element
    };
    var newImageId = lmViewer.fn.getDicom(_getDicomObj);

    cornerstone.loadAndCacheImage(newImageId).then(function (image) {
      cornerstone.displayImage(element, image);
      var viewport = cornerstone.getEnabledElement(element).viewport;
      var _obj = {
        element: element,
        image: undefined
      };
      var seriesNum = lmViewer.fn.getImgIndex(_obj).series;
      lmViewer.data.initialWL[seriesNum] = image.windowCenter;
      lmViewer.data.initialWW[seriesNum] = image.windowWidth;

      viewport.voi.windowCenter = 50;
      viewport.voi.windowWidth = 350;

      // element 的行列索引
      var eleRowIndex = element.id.substring(
        element.id.indexOf('image') + 5,
        element.id.indexOf('image') + 6);
      var eleColumnIndex = element.id.substring(
        element.id.indexOf('image') + 6);
      eleRowIndex = parseInt(eleRowIndex);
      eleColumnIndex = parseInt(eleColumnIndex);

      var elementIdx = 0;
      if ('' != lmViewer.data.sort && 1 == lmViewer.data.iWindowVNum && 1 == lmViewer.data.iWindowHNum) {
        elementIdx = parseInt(lmViewer.data.sort);
      } else {
        elementIdx = eleRowIndex * lmViewer.data.iWindowVNum + eleColumnIndex;
      }

      lmViewer.data.globalWL[elementIdx] = 50;
      lmViewer.data.globalWW[elementIdx] = 350;

      cornerstone.setViewport(element, viewport);
      lmViewer.fn.triggerResize();
      $('#modalProgressGlobal').modal('hide');
    });

    cornerstoneTools.wwwc.activate(element, 1);
    $(element).off('CornerstoneToolsMouseDrag');
    $(element).on('CornerstoneToolsMouseDrag', mouseDragWWWL);

    //							var viewport = cornerstone.getViewport(element);
    //							viewport.voi.windowWidth = 170;
    //							viewport.voi.windowCenter = 35;
    //							cornerstone.setViewport(element, viewport);
  };

  ui.WindowLevelBoneClick = function (e) {
    disableAllTools();
    lmViewer.ui.recoverButtonColor();
    $('#WindowLevelBone').css('background-color', 'gray');
    //			$('#modalProgressGlobal').modal('show');
    $('#imageContainer').addClass('adjust');

    lmViewer.data.contrastButtonPressed = true;
    var _getDicomObj = {
      element: element
    };
    var newImageId = lmViewer.fn.getDicom(_getDicomObj);

    cornerstone.loadAndCacheImage(newImageId).then(function (image) {
      cornerstone.displayImage(element, image);
      var viewport = cornerstone.getEnabledElement(element).viewport;
      var _obj = {
        element: element,
        image: undefined
      };
      var seriesNum = lmViewer.fn.getImgIndex(_obj).series;
      lmViewer.data.initialWL[seriesNum] = image.windowCenter;
      lmViewer.data.initialWW[seriesNum] = image.windowWidth;
      ;

      viewport.voi.windowCenter = 300;
      viewport.voi.windowWidth = 1500;

      // element 的行列索引
      var eleRowIndex = element.id.substring(
        element.id.indexOf('image') + 5,
        element.id.indexOf('image') + 6);
      var eleColumnIndex = element.id.substring(
        element.id.indexOf('image') + 6);
      eleRowIndex = parseInt(eleRowIndex);
      eleColumnIndex = parseInt(eleColumnIndex);

      var elementIdx = 0;
      if ('' != lmViewer.data.sort && 1 == lmViewer.data.iWindowVNum && 1 == lmViewer.data.iWindowHNum) {
        elementIdx = parseInt(lmViewer.data.sort);
      } else {
        elementIdx = eleRowIndex * lmViewer.data.iWindowVNum + eleColumnIndex;
      }

      lmViewer.data.globalWL[elementIdx] = 300;
      lmViewer.data.globalWW[elementIdx] = 1500;

      cornerstone.setViewport(element, viewport);
      lmViewer.fn.triggerResize();
      $('#modalProgressGlobal').modal('hide');
    });

    cornerstoneTools.wwwc.activate(element, 1);
    $(element).off('CornerstoneToolsMouseDrag');
    $(element).on('CornerstoneToolsMouseDrag', mouseDragWWWL);

    //							var viewport = cornerstone.getViewport(element);
    //							viewport.voi.windowWidth = 1500;
    //							viewport.voi.windowCenter = 300;
    //							cornerstone.setViewport(element, viewport);
  };

  ui.showLoading = function () {
    // $('#loading').show();
    showLoading();
  };


  ui.hideLoading = function () {
    // $('#loading').hide();
    hideLoading();
  };
})(lmViewer);

lmViewer.ctrl.init();

